Merge m-c to inbound, a=merge
authorWes Kocher <wkocher@mozilla.com>
Fri, 17 Feb 2017 13:51:01 -0800
changeset 372816 11554dd8d296e9d5460db61df14e506861a598bc
parent 372815 da9836d57e73a80750bd5cf43a9d1ee6bf3331dd (current diff)
parent 372650 d11c29c1db3a1bc96ad5792ebf8a89b2fbadcf85 (diff)
child 372817 088265acb42e053e3ed5486be163460d806dd5b1
push id10863
push userjlorenzo@mozilla.com
push dateMon, 06 Mar 2017 23:02:23 +0000
treeherdermozilla-aurora@0931190cd725 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersmerge
milestone54.0a1
Merge m-c to inbound, a=merge MozReview-Commit-ID: 18xg2cleATb
dom/media/platforms/agnostic/gmp/MediaDataDecoderProxy.cpp
dom/media/platforms/agnostic/gmp/MediaDataDecoderProxy.h
dom/media/platforms/android/MediaCodecDataDecoder.cpp
dom/media/platforms/android/MediaCodecDataDecoder.h
extensions/auth/nsHttpNegotiateAuth.cpp
layout/base/PresShell.cpp
layout/base/PresShell.h
layout/base/nsIPresShell.h
layout/reftests/svg/reftest-stylo.list
mobile/android/base/java/org/mozilla/gecko/media/LocalMediaDrmBridge.java
services/.eslintrc.js
--- a/.eslintignore
+++ b/.eslintignore
@@ -93,17 +93,16 @@ devtools/client/shared/*.jsm
 devtools/client/shared/components/reps/reps.js
 devtools/client/shared/webgl-utils.js
 devtools/client/shared/widgets/*.jsm
 devtools/client/webaudioeditor/**
 devtools/client/webconsole/net/**
 devtools/client/webconsole/test/**
 devtools/client/webconsole/console-output.js
 devtools/client/webconsole/hudservice.js
-devtools/client/webconsole/utils.js
 devtools/client/webconsole/webconsole-connection-proxy.js
 devtools/client/webconsole/webconsole.js
 devtools/client/webide/**
 !devtools/client/webide/components/webideCli.js
 devtools/server/actors/webconsole.js
 devtools/server/actors/object.js
 devtools/server/actors/script.js
 devtools/server/actors/styleeditor.js
--- a/browser/app/blocklist.xml
+++ b/browser/app/blocklist.xml
@@ -2264,16 +2264,26 @@
       <match exp="(NPSWF32\.dll)|(Flash\ Player\.plugin)" name="filename"/>
       <infoURL>https://get.adobe.com/flashplayer/</infoURL>
       <versionRange maxVersion="10.3.183.18.999" minVersion="10.3" severity="0" vulnerabilitystatus="1">
         <targetApplication id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
           <versionRange maxVersion="17.0.*" minVersion="17.0.4"/>
         </targetApplication>
       </versionRange>
     </pluginItem>
+    <pluginItem blockID="3f136e56-4c93-4619-8c0d-d86258c1065d">
+      <match exp="(nppdf32\.dll)|(AdobePDFViewerNPAPI\.plugin)" name="filename"/>
+      <infoURL>https://get.adobe.com/reader/</infoURL>
+      <versionRange maxVersion="15.006.30244" minVersion="15.006" severity="1" vulnerabilitystatus="1"/>
+    </pluginItem>
+    <pluginItem blockID="43b45ad8-a373-42c1-89c6-64e2746885e5">
+      <match exp="(nppdf32\.dll)|(AdobePDFViewerNPAPI\.plugin)" name="filename"/>
+      <infoURL>https://get.adobe.com/reader/</infoURL>
+      <versionRange maxVersion="15.020.20042" minVersion="15.020" severity="1" vulnerabilitystatus="1"/>
+    </pluginItem>
     <pluginItem blockID="p366">
       <match exp="Scorch\.plugin" name="filename"/>
       <versionRange maxVersion="6.2.0" minVersion="6.2.0" severity="1"/>
     </pluginItem>
     <pluginItem blockID="p936" os="Linux">
       <match exp="libflashplayer\.so" name="filename"/>
       <infoURL>https://get.adobe.com/flashplayer/</infoURL>
       <versionRange maxVersion="11.2.202.480" minVersion="11.2.202.468" severity="0" vulnerabilitystatus="1"/>
@@ -2344,16 +2354,21 @@
       <match exp="Java\(TM\) Platform SE 7 U(1[6-9]|2[0-4])(\s[^\d\._U]|$)" name="name"/>
       <match exp="npjp2\.dll" name="filename"/>
       <versionRange severity="0" vulnerabilitystatus="1">
         <targetApplication id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
           <versionRange maxVersion="*" minVersion="17.0"/>
         </targetApplication>
       </versionRange>
     </pluginItem>
+    <pluginItem blockID="59c31ade-88d6-4b22-8601-5316f82e3977">
+      <match exp="(nppdf32\.dll)|(AdobePDFViewerNPAPI\.plugin)" name="filename"/>
+      <infoURL>https://get.adobe.com/reader/</infoURL>
+      <versionRange maxVersion="11.0.18" minVersion="11.0" severity="1" vulnerabilitystatus="1"/>
+    </pluginItem>
     <pluginItem blockID="p1004">
       <match exp="Unity Web Player\.plugin" name="filename"/>
       <match exp="^($|Unity Web Player version 5.0(\.([0-2]|3f1))?[^0-9.])" name="description"/>
       <versionRange severity="0" vulnerabilitystatus="1"/>
     </pluginItem>
     <pluginItem blockID="p459">
       <match exp="JavaAppletPlugin\.plugin" name="filename"/>
       <versionRange maxVersion="Java 7 Update 44" minVersion="Java 7 Update 25" severity="0" vulnerabilitystatus="1">
@@ -2804,17 +2819,17 @@
     </pluginItem>
     <pluginItem blockID="p574">
       <match exp="NPDjVu\.plugin" name="filename"/>
       <versionRange maxVersion="6.1.1" minVersion="0" severity="0" vulnerabilitystatus="1"/>
     </pluginItem>
     <pluginItem blockID="p28">
       <match exp="NPFFAddOn.dll" name="filename"/>
     </pluginItem>
-    <pluginItem blockID="p1421">
+    <pluginItem blockID="p1421" os="Linux">
       <match exp="libflashplayer\.so" name="filename"/>
       <infoURL>https://get.adobe.com/flashplayer/</infoURL>
       <versionRange maxVersion="23.0.0.207" minVersion="11.2.202.643" severity="0" vulnerabilitystatus="1"/>
     </pluginItem>
     <pluginItem blockID="p302">
       <match exp="Java\(TM\) Plug-in 1\.6\.0_(39|40|41)([^\d\._]|$)" name="name"/>
       <match exp="libnpjp2\.so" name="filename"/>
       <versionRange severity="0" vulnerabilitystatus="1">
--- a/browser/base/content/aboutTabCrashed.js
+++ b/browser/base/content/aboutTabCrashed.js
@@ -1,12 +1,14 @@
 /* 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/. */
 
+/* eslint-env mozilla/frame-script */
+
 var AboutTabCrashed = {
   /**
    * This can be set to true once this page receives a message from the
    * parent saying whether or not a crash report is available.
    */
   hasReport: false,
 
   /**
--- a/browser/base/content/content.js
+++ b/browser/base/content/content.js
@@ -1,16 +1,18 @@
 /* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
 /* 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 content script should work in any browser or iframe and should not
  * depend on the frame being contained in tabbrowser. */
 
+/* eslint-env mozilla/frame-script */
+
 var {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
 
 Cu.import("resource://gre/modules/XPCOMUtils.jsm");
 Cu.import("resource://gre/modules/Services.jsm");
 Cu.import("resource:///modules/ContentWebRTC.jsm");
 Cu.import("resource:///modules/ContentObservers.jsm");
 Cu.import("resource://gre/modules/InlineSpellChecker.jsm");
 Cu.import("resource://gre/modules/InlineSpellCheckerContent.jsm");
--- a/browser/base/content/social-content.js
+++ b/browser/base/content/social-content.js
@@ -1,15 +1,17 @@
 /* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
 /* 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 content script is intended for use by iframes in the share panel. */
 
+/* eslint-env mozilla/frame-script */
+
 var {interfaces: Ci, utils: Cu} = Components;
 
 Cu.import("resource://gre/modules/XPCOMUtils.jsm");
 Cu.import("resource://gre/modules/Services.jsm");
 
 // social frames are always treated as app tabs
 docShell.isAppTab = true;
 
--- a/browser/base/content/tab-content.js
+++ b/browser/base/content/tab-content.js
@@ -1,15 +1,17 @@
 /* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
 /* 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 content script contains code that requires a tab browser. */
 
+/* eslint-env mozilla/frame-script */
+
 var {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
 
 Cu.import("resource://gre/modules/XPCOMUtils.jsm");
 Cu.import("resource://gre/modules/Services.jsm");
 Cu.import("resource://gre/modules/ExtensionContent.jsm");
 
 XPCOMUtils.defineLazyModuleGetter(this, "E10SUtils",
   "resource:///modules/E10SUtils.jsm");
--- a/browser/base/content/test/general/aboutHome_content_script.js
+++ b/browser/base/content/test/general/aboutHome_content_script.js
@@ -1,6 +1,8 @@
 /* Any copyright is dedicated to the Public Domain.
  * http://creativecommons.org/publicdomain/zero/1.0/ */
 
+/* eslint-env mozilla/frame-script */
+
 addMessageListener("AboutHome:SearchTriggered", function(msg) {
   sendAsyncMessage("AboutHomeTest:CheckRecordedSearch", msg.data);
 });
--- a/browser/base/content/test/general/browser.ini
+++ b/browser/base/content/test/general/browser.ini
@@ -81,16 +81,17 @@ support-files =
   browser_webext_nopermissions.xpi
   browser_webext_update1.xpi
   browser_webext_update2.xpi
   browser_webext_update_icon1.xpi
   browser_webext_update_icon2.xpi
   browser_webext_update_perms1.xpi
   browser_webext_update_perms2.xpi
   browser_webext_update.json
+  browser_webext_search.xml
   !/image/test/mochitest/blue.png
   !/toolkit/content/tests/browser/common/mockTransfer.js
   !/toolkit/modules/tests/browser/metadata_*.html
   !/toolkit/mozapps/extensions/test/xpinstall/amosigned.xpi
   !/toolkit/mozapps/extensions/test/xpinstall/corrupt.xpi
   !/toolkit/mozapps/extensions/test/xpinstall/incompatible.xpi
   !/toolkit/mozapps/extensions/test/xpinstall/installtrigger.html
   !/toolkit/mozapps/extensions/test/xpinstall/redirect.sjs
--- a/browser/base/content/test/general/browser_accesskeys.js
+++ b/browser/base/content/test/general/browser_accesskeys.js
@@ -1,8 +1,10 @@
+/* eslint-env mozilla/frame-script */
+
 add_task(function *() {
   yield pushPrefs(["ui.key.contentAccess", 5], ["ui.key.chromeAccess", 5]);
 
   const gPageURL1 = "data:text/html,<body><p>" +
                     "<button id='button' accesskey='y'>Button</button>" +
                     "<input id='checkbox' type='checkbox' accesskey='z'>Checkbox" +
                     "</p></body>";
   let tab1 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, gPageURL1);
--- a/browser/base/content/test/general/browser_backButtonFitts.js
+++ b/browser/base/content/test/general/browser_backButtonFitts.js
@@ -1,12 +1,14 @@
 /* Any copyright is dedicated to the Public Domain.
  * http://creativecommons.org/publicdomain/zero/1.0/
  */
 
+/* eslint-env mozilla/frame-script */
+
 add_task(function* () {
   let firstLocation = "http://example.org/browser/browser/base/content/test/general/dummy_page.html";
   yield BrowserTestUtils.openNewForegroundTab(gBrowser, firstLocation);
 
   yield ContentTask.spawn(gBrowser.selectedBrowser, {}, function* () {
     // Push the state before maximizing the window and clicking below.
     content.history.pushState("page2", "page2", "page2");
 
--- a/browser/base/content/test/general/browser_documentnavigation.js
+++ b/browser/base/content/test/general/browser_documentnavigation.js
@@ -1,14 +1,16 @@
 /*
  * This test checks that focus is adjusted properly in a browser when pressing F6 and Shift+F6.
  * There are additional tests in dom/tests/mochitest/chrome/test_focus_docnav.xul which test
  * non-browser cases.
  */
 
+/* eslint-env mozilla/frame-script */
+
 var testPage1 = "data:text/html,<html id='html1'><body id='body1'><button id='button1'>Tab 1</button></body></html>";
 var testPage2 = "data:text/html,<html id='html2'><body id='body2'><button id='button2'>Tab 2</button></body></html>";
 var testPage3 = "data:text/html,<html id='html3'><body id='body3' contenteditable='true'><button id='button3'>Tab 3</button></body></html>";
 
 var fm = Services.focus;
 
 function* expectFocusOnF6(backward, expectedDocument, expectedElement, onContent, desc) {
   let focusChangedInChildResolver = null;
--- a/browser/base/content/test/general/browser_domFullscreen_fullscreenMode.js
+++ b/browser/base/content/test/general/browser_domFullscreen_fullscreenMode.js
@@ -1,8 +1,10 @@
+/* eslint-env mozilla/frame-script */
+
 "use strict";
 
 var gMessageManager;
 
 function frameScript() {
   addMessageListener("Test:RequestFullscreen", () => {
     content.document.body.requestFullscreen();
   });
--- a/browser/base/content/test/general/browser_e10s_switchbrowser.js
+++ b/browser/base/content/test/general/browser_e10s_switchbrowser.js
@@ -1,8 +1,10 @@
+/* eslint-env mozilla/frame-script */
+
 requestLongerTimeout(2);
 
 const DUMMY_PATH = "browser/browser/base/content/test/general/dummy_page.html";
 
 const gExpectedHistory = {
   index: -1,
   entries: []
 };
--- a/browser/base/content/test/general/browser_extension_permissions.js
+++ b/browser/base/content/test/general/browser_extension_permissions.js
@@ -1,31 +1,41 @@
 "use strict";
 
+// See but 1340586 for proposal to reorganize permissions tests to
+// get rid of this...
+requestLongerTimeout(2);
+
 const BASE = getRootDirectory(gTestPath)
   .replace("chrome://mochitests/content/", "https://example.com/");
 
 const INSTALL_PAGE = `${BASE}/file_install_extensions.html`;
 const PERMS_XPI = "browser_webext_permissions.xpi";
 const NO_PERMS_XPI = "browser_webext_nopermissions.xpi";
 const ID = "permissions@test.mozilla.org";
 
-const DEFAULT_EXTENSION_ICON = "chrome://browser/content/extension.svg";
-
 Services.perms.add(makeURI("https://example.com/"), "install",
                    Services.perms.ALLOW_ACTION);
 
 registerCleanupFunction(async function() {
   let addon = await AddonManager.getAddonByID(ID);
   if (addon) {
     ok(false, `Addon ${ID} was still installed at the end of the test`);
     addon.uninstall();
   }
 });
 
+function isDefaultIcon(icon) {
+  // These are basically the same icon, but code within webextensions
+  // generates references to the former and generic add-ons manager code
+  // generates referces to the latter.
+  return (icon == "chrome://browser/content/extension.svg" ||
+          icon == "chrome://mozapps/skin/extensions/extensionGeneric.svg");
+}
+
 function promisePopupNotificationShown(name) {
   return new Promise(resolve => {
     function popupshown() {
       let notification = PopupNotifications.getNotification(name);
       if (!notification) { return; }
 
       ok(notification, `${name} notification shown`);
       ok(PopupNotifications.isPanelOpen, "notification panel open");
@@ -51,17 +61,17 @@ function checkNotification(panel, filena
     ok(icon.startsWith("jar:file://"), "Icon is a jar url");
     ok(icon.endsWith("/icon.png"), "Icon is icon.png inside a jar");
 
     is(header.getAttribute("hidden"), "", "Permission list header is visible");
     is(ul.childElementCount, 4, "Permissions list has 4 entries");
     // Real checking of the contents here is deferred until bug 1316996 lands
   } else if (filename == NO_PERMS_XPI) {
     // This extension has no icon, it should have the default
-    is(icon, DEFAULT_EXTENSION_ICON, "Icon is the default extension icon");
+    ok(isDefaultIcon(icon), "Icon is the default extension icon");
 
     is(header.getAttribute("hidden"), "true", "Permission list header is hidden");
     is(ul.childElementCount, 0, "Permissions list has 0 entries");
   }
 }
 
 // Navigate the current tab to the given url and return a Promise
 // that resolves when the page is loaded.
@@ -101,16 +111,55 @@ const INSTALL_FUNCTIONS = [
 
     await BrowserOpenAddonsMgr("addons://list/extension");
     let contentWin = gBrowser.selectedTab.linkedBrowser.contentWindow;
 
     // Do the install...
     contentWin.gViewController.doCommand("cmd_installFromFile");
     MockFilePicker.cleanup();
   },
+
+  async function installSearch(filename) {
+    await SpecialPowers.pushPrefEnv({set: [
+      ["extensions.getAddons.maxResults", 10],
+      ["extensions.getAddons.search.url", `${BASE}/browser_webext_search.xml`],
+    ]});
+
+    let win = await BrowserOpenAddonsMgr("addons://list/extension");
+
+    let searchResultsPromise = new Promise(resolve => {
+      win.document.addEventListener("ViewChanged", resolve, {once: true});
+    });
+    let search = win.document.getElementById("header-search");
+    search.focus();
+    search.value = "search text";
+    EventUtils.synthesizeKey("VK_RETURN", {}, win);
+
+    await searchResultsPromise;
+    ok(win.gViewController.currentViewId.startsWith("addons://search"),
+       "about:addons is displaying search results");
+
+    let list = win.document.getElementById("search-list");
+    let item = null;
+    for (let child of list.childNodes) {
+      if (child.nodeName == "richlistitem" &&
+          child.mAddon.install.sourceURI.path.endsWith(filename)) {
+            item = child;
+            break;
+      }
+    }
+    ok(item, `Found ${filename} in search results`);
+
+    // abracadabara XBL
+    item.clientTop;
+
+    let install = win.document.getAnonymousElementByAttribute(item, "anonid", "install-status");
+    let button = win.document.getAnonymousElementByAttribute(install, "anonid", "install-remote-btn");
+    EventUtils.synthesizeMouseAtCenter(button, {}, win);
+  },
 ];
 
 add_task(function* () {
   yield SpecialPowers.pushPrefEnv({set: [
     ["extensions.webapi.testing", true],
     ["extensions.install.requireBuiltInCerts", false],
 
     // XXX remove this when prompts are enabled by default
--- a/browser/base/content/test/general/browser_offlineQuotaNotification.js
+++ b/browser/base/content/test/general/browser_offlineQuotaNotification.js
@@ -1,13 +1,15 @@
 /**
  * Any copyright is dedicated to the Public Domain.
  * http://creativecommons.org/publicdomain/zero/1.0/
  */
 
+/* eslint-env mozilla/frame-script */
+
 // Test offline quota warnings - must be run as a mochitest-browser test or
 // else the test runner gets in the way of notifications due to bug 857897.
 
 const URL = "http://mochi.test:8888/browser/browser/base/content/test/general/offlineQuotaNotification.html";
 
 registerCleanupFunction(function() {
   // Clean up after ourself
   let uri = Services.io.newURI(URL);
--- a/browser/base/content/test/general/browser_restore_isAppTab.js
+++ b/browser/base/content/test/general/browser_restore_isAppTab.js
@@ -1,11 +1,13 @@
 /* Any copyright is dedicated to the Public Domain.
  * http://creativecommons.org/publicdomain/zero/1.0/ */
 
+/* eslint-env mozilla/frame-script */
+
 const {TabStateFlusher} = Cu.import("resource:///modules/sessionstore/TabStateFlusher.jsm", {});
 
 const DUMMY = "http://example.com/browser/browser/base/content/test/general/dummy_page.html";
 
 function getMinidumpDirectory() {
   let dir = Services.dirsvc.get("ProfD", Ci.nsIFile);
   dir.append("minidumps");
   return dir;
--- a/browser/base/content/test/general/browser_tab_dragdrop.js
+++ b/browser/base/content/test/general/browser_tab_dragdrop.js
@@ -1,8 +1,10 @@
+/* eslint-env mozilla/frame-script */
+
 function swapTabsAndCloseOther(a, b) {
   gBrowser.swapBrowsersAndCloseOther(gBrowser.tabs[b], gBrowser.tabs[a]);
 }
 
 var getClicks = function(tab) {
   return ContentTask.spawn(tab.linkedBrowser, {}, function() {
     return content.wrappedJSObject.clicks;
   });
--- a/browser/base/content/test/general/browser_tabfocus.js
+++ b/browser/base/content/test/general/browser_tabfocus.js
@@ -1,12 +1,14 @@
 /*
  * This test checks that focus is adjusted properly when switching tabs.
  */
 
+/* eslint-env mozilla/frame-script */
+
 var testPage1 = "<html id='html1'><body id='body1'><button id='button1'>Tab 1</button></body></html>";
 var testPage2 = "<html id='html2'><body id='body2'><button id='button2'>Tab 2</button></body></html>";
 var testPage3 = "<html id='html3'><body id='body3'><button id='button3'>Tab 3</button></body></html>";
 
 const fm = Services.focus;
 
 function EventStore() {
   this["main-window"] = [];
new file mode 100644
--- /dev/null
+++ b/browser/base/content/test/general/browser_webext_search.xml
@@ -0,0 +1,51 @@
+<?xml version="1.0" encoding="utf-8" ?>
+<searchresults total_results="2">
+  <addon>
+    <name>permissions test</name>
+    <type id='1'>Extension</type>
+    <guid>permissions@tests.mozilla.org</guid>
+    <version>1.1</version>
+    <authors>
+      <author>
+        <name>Test Creator</name>
+        <link>http://example.com/creator.html</link>
+      </author>
+    </authors>
+    <status id='4'>Public</status>
+    <compatible_applications>
+      <application>
+        <name>Firefox</name>
+        <appID>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</appID>
+        <min_version>0</min_version>
+        <max_version>*</max_version>
+      </application>
+    </compatible_applications>
+    <compatible_os>ALL</compatible_os>
+    <install size="1">https://example.com/browser/browser/base/content/test/general/browser_webext_permissions.xpi</install>
+  </addon>
+
+  <addon>
+    <name>no permissions</name>
+    <type id='1'>Extension</type>
+    <guid>nopermissions@tests.mozilla.org</guid>
+    <version>1.0</version>
+    <authors>
+      <author>
+        <name>Test Creator</name>
+        <link>http://example.com/creator.html</link>
+      </author>
+    </authors>
+    <status id='4'>Public</status>
+    <compatible_applications>
+      <application>
+        <name>Firefox</name>
+        <appID>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</appID>
+        <min_version>0</min_version>
+        <max_version>*</max_version>
+      </application>
+    </compatible_applications>
+    <compatible_os>ALL</compatible_os>
+    <install size="1">https://example.com/browser/browser/base/content/test/general/browser_webext_nopermissions.xpi</install>
+  </addon>
+</searchresults>
+
--- a/browser/base/content/test/general/browser_windowactivation.js
+++ b/browser/base/content/test/general/browser_windowactivation.js
@@ -1,12 +1,14 @@
 /*
  * This test checks that window activation state is set properly with multiple tabs.
  */
 
+/* eslint-env mozilla/frame-script */
+
 var testPage = "data:text/html,<body><style>:-moz-window-inactive { background-color: red; }</style><div id='area'></div></body>";
 
 var colorChangeNotifications = 0;
 var otherWindow;
 
 var browser1, browser2;
 
 function test() {
--- a/browser/base/content/test/general/contentSearchUI.js
+++ b/browser/base/content/test/general/contentSearchUI.js
@@ -1,11 +1,13 @@
 /* Any copyright is dedicated to the Public Domain.
  * http://creativecommons.org/publicdomain/zero/1.0/ */
 
+/* eslint-env mozilla/frame-script */
+
 "use strict";
 
 (function() {
 
 const TEST_MSG = "ContentSearchUIControllerTest";
 const ENGINE_NAME = "browser_searchSuggestionEngine searchSuggestionEngine.xml";
 var gController;
 
--- a/browser/base/content/test/general/content_aboutAccounts.js
+++ b/browser/base/content/test/general/content_aboutAccounts.js
@@ -1,15 +1,17 @@
 /* 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 file is loaded as a "content script" for browser_aboutAccounts tests
 "use strict";
 
+/* eslint-env mozilla/frame-script */
+
 var {interfaces: Ci, utils: Cu} = Components;
 
 addEventListener("load", function load(event) {
   if (event.target != content.document) {
     return;
   }
 //  content.document.removeEventListener("load", load, true);
   sendAsyncMessage("test:document:load");
--- a/browser/base/content/test/general/head.js
+++ b/browser/base/content/test/general/head.js
@@ -1,8 +1,10 @@
+/* eslint-env mozilla/frame-script */
+
 Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
 
 XPCOMUtils.defineLazyModuleGetter(this, "Promise",
   "resource://gre/modules/Promise.jsm");
 XPCOMUtils.defineLazyModuleGetter(this, "Task",
   "resource://gre/modules/Task.jsm");
 XPCOMUtils.defineLazyModuleGetter(this, "PlacesUtils",
   "resource://gre/modules/PlacesUtils.jsm");
--- a/browser/base/content/test/newtab/browser_newtab_bug734043.js
+++ b/browser/base/content/test/newtab/browser_newtab_bug734043.js
@@ -1,11 +1,13 @@
 /* Any copyright is dedicated to the Public Domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
+/* eslint-env mozilla/frame-script */
+
 add_task(function* () {
   yield setLinks("0,1,2,3,4,5,6,7,8");
   setPinnedLinks("");
 
   yield* addNewTabPageTab();
   yield* checkGrid("0,1,2,3,4,5,6,7,8");
 
   yield ContentTask.spawn(gBrowser.selectedBrowser, {}, function* () {
--- a/browser/base/content/test/newtab/browser_newtab_bug991111.js
+++ b/browser/base/content/test/newtab/browser_newtab_bug991111.js
@@ -1,11 +1,13 @@
 /* Any copyright is dedicated to the Public Domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
+/* eslint-env mozilla/frame-script */
+
 add_task(function* () {
   // set max rows to 1, to avoid scroll events by clicking middle button
   yield pushPrefs(["browser.newtabpage.rows", 1]);
   yield setLinks("-1");
   yield* addNewTabPageTab();
   // we need a second newtab to honor max rows
   yield* addNewTabPageTab();
 
--- a/browser/base/content/test/newtab/browser_newtab_bug998387.js
+++ b/browser/base/content/test/newtab/browser_newtab_bug998387.js
@@ -1,11 +1,13 @@
 /* Any copyright is dedicated to the Public Domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
+/* eslint-env mozilla/frame-script */
+
 add_task(function* () {
   // set max rows to 1, to avoid scroll events by clicking middle button
   yield pushPrefs(["browser.newtabpage.rows", 1]);
   yield setLinks("0");
   yield* addNewTabPageTab();
   // we need a second newtab to honor max rows
   yield* addNewTabPageTab();
 
--- a/browser/base/content/test/newtab/browser_newtab_search.js
+++ b/browser/base/content/test/newtab/browser_newtab_search.js
@@ -1,11 +1,13 @@
 /* Any copyright is dedicated to the Public Domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
+/* eslint-env mozilla/frame-script */
+
 // See browser/components/search/test/browser_*_behavior.js for tests of actual
 // searches.
 
 Cu.import("resource://gre/modules/Task.jsm");
 
 const ENGINE_NO_LOGO = {
   name: "searchEngineNoLogo.xml",
   numLogos: 0,
--- a/browser/base/content/test/newtab/content-reflows.js
+++ b/browser/base/content/test/newtab/content-reflows.js
@@ -1,12 +1,14 @@
 /* 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/. */
 
+/* eslint-env mozilla/frame-script */
+
 (function() {
   "use strict";
 
   const Ci = Components.interfaces;
 
   docShell.addWeakReflowObserver({
     reflow() {
       // Gather information about the current code path.
--- a/browser/base/content/test/popupNotifications/browser_popupNotification_5.js
+++ b/browser/base/content/test/popupNotifications/browser_popupNotification_5.js
@@ -334,16 +334,18 @@ var tests = [
   // Test clicking the anchor icon.
   // Clicking the anchor of an already visible persistent notification should
   // focus the main action button, but not cause additional showing/shown event
   // callback calls.
   // Clicking the anchor of a dismissed notification should show it, even when
   // the currently displayed notification is a persistent one.
   { id: "Test#11",
     *run() {
+      yield SpecialPowers.pushPrefEnv({"set": [["accessibility.tabfocus", 7]]});
+
       function clickAnchor(notifyObj) {
         let anchor = document.getElementById(notifyObj.anchorID);
         EventUtils.synthesizeMouseAtCenter(anchor, {});
       }
 
       let popup = PopupNotifications.panel;
 
       let notifyObj1 = new BasicNotification(this.id);
@@ -354,20 +356,21 @@ var tests = [
       let notification1 = showNotification(notifyObj1);
       yield shown;
       checkPopup(popup, notifyObj1);
       ok(!notifyObj1.dismissalCallbackTriggered,
          "Should not have dismissed the notification");
       notifyObj1.shownCallbackTriggered = false;
       notifyObj1.showingCallbackTriggered = false;
 
-      // Click the anchor. This should focus the primary button, but
-      // not call event callbacks on the notification object.
+      // Click the anchor. This should focus the closebutton
+      // (because it's the first focusable element), but not
+      // call event callbacks on the notification object.
       clickAnchor(notifyObj1);
-      is(document.activeElement, popup.childNodes[0].button);
+      is(document.activeElement, popup.childNodes[0].closebutton);
       ok(!notifyObj1.dismissalCallbackTriggered,
          "Should not have dismissed the notification");
       ok(!notifyObj1.shownCallbackTriggered,
          "Should have triggered the shown event again");
       ok(!notifyObj1.showingCallbackTriggered,
          "Should have triggered the showing event again");
 
       // Add another notification.
--- a/browser/base/content/test/popupNotifications/browser_popupNotification_keyboard.js
+++ b/browser/base/content/test/popupNotifications/browser_popupNotification_keyboard.js
@@ -48,27 +48,88 @@ var tests = [
       ok(this.notifyObj.dismissalCallbackTriggered, "dismissal callback triggered");
       ok(!this.notifyObj.removedCallbackTriggered, "removed callback was not triggered");
       this.notification.remove();
     }
   },
   // Test that the space key on an anchor element focuses an active notification
   { id: "Test#3",
     *run() {
+      yield SpecialPowers.pushPrefEnv({"set": [["accessibility.tabfocus", 7]]});
       this.notifyObj = new BasicNotification(this.id);
       this.notifyObj.anchorID = "geo-notification-icon";
       this.notifyObj.addOptions({
-        persistent: true
+        persistent: true,
       });
       this.notification = showNotification(this.notifyObj);
     },
     *onShown(popup) {
       checkPopup(popup, this.notifyObj);
       let anchor = document.getElementById(this.notifyObj.anchorID);
       anchor.focus();
       is(document.activeElement, anchor);
       EventUtils.synthesizeKey(" ", {});
-      is(document.activeElement, popup.childNodes[0].button);
+      is(document.activeElement, popup.childNodes[0].closebutton);
       this.notification.remove();
     },
     onHidden(popup) { }
   },
+  // Test that you can switch between active notifications with the space key
+  // and that the notification is focused on selection.
+  { id: "Test#4",
+    *run() {
+      yield SpecialPowers.pushPrefEnv({"set": [["accessibility.tabfocus", 7]]});
+
+      let notifyObj1 = new BasicNotification(this.id);
+      notifyObj1.id += "_1";
+      notifyObj1.anchorID = "default-notification-icon";
+      notifyObj1.addOptions({
+        hideClose: true,
+        checkbox: {
+          label: "Test that elements inside the panel can be focused",
+        },
+        persistent: true,
+      });
+      let opened = waitForNotificationPanel();
+      let notification1 = showNotification(notifyObj1);
+      yield opened;
+
+      let notifyObj2 = new BasicNotification(this.id);
+      notifyObj2.id += "_2";
+      notifyObj2.anchorID = "geo-notification-icon";
+      notifyObj2.addOptions({
+        persistent: true,
+      });
+      opened = waitForNotificationPanel();
+      let notification2 = showNotification(notifyObj2);
+      let popup = yield opened;
+
+      // Make sure notification 2 is visible
+      checkPopup(popup, notifyObj2);
+
+      // Activate the anchor for notification 1 and wait until it's shown.
+      let anchor = document.getElementById(notifyObj1.anchorID);
+      anchor.focus();
+      is(document.activeElement, anchor);
+      opened = waitForNotificationPanel();
+      EventUtils.synthesizeKey(" ", {});
+      popup = yield opened;
+      checkPopup(popup, notifyObj1);
+
+      is(document.activeElement, popup.childNodes[0].checkbox);
+
+      // Activate the anchor for notification 2 and wait until it's shown.
+      anchor = document.getElementById(notifyObj2.anchorID);
+      anchor.focus();
+      is(document.activeElement, anchor);
+      opened = waitForNotificationPanel();
+      EventUtils.synthesizeKey(" ", {});
+      popup = yield opened;
+      checkPopup(popup, notifyObj2);
+
+      is(document.activeElement, popup.childNodes[0].closebutton);
+
+      notification1.remove();
+      notification2.remove();
+      goNext();
+    },
+  },
 ];
--- a/browser/base/content/test/social/browser_share.js
+++ b/browser/base/content/test/social/browser_share.js
@@ -1,8 +1,9 @@
+/* eslint-env mozilla/frame-script */
 
 var SocialService = Cu.import("resource:///modules/SocialService.jsm", {}).SocialService;
 
 var baseURL = "https://example.com/browser/browser/base/content/test/social/";
 
 var manifest = { // normal provider
   name: "provider 1",
   origin: "https://example.com",
--- a/browser/base/content/test/social/social_crash_content_helper.js
+++ b/browser/base/content/test/social/social_crash_content_helper.js
@@ -1,11 +1,13 @@
 /* Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/publicdomain/zero/1.0/ */
 
+/* eslint-env mozilla/frame-script */
+
 var Cu = Components.utils;
 
 // Ideally we would use CrashTestUtils.jsm, but that's only available for
 // xpcshell tests - so we just copy a ctypes crasher from it.
 Cu.import("resource://gre/modules/ctypes.jsm");
 var crash = function() { // this will crash when called.
   let zero = new ctypes.intptr_t(8);
   let badptr = ctypes.cast(zero, ctypes.PointerType(ctypes.int32_t));
--- a/browser/base/content/test/urlbar/browser_urlbarAutoFillTrimURLs.js
+++ b/browser/base/content/test/urlbar/browser_urlbarAutoFillTrimURLs.js
@@ -10,40 +10,107 @@ add_task(function* setup() {
     Services.prefs.clearUserPref(PREF_AUTOFILL);
     yield PlacesTestUtils.clearHistory();
     gURLBar.handleRevert();
   });
   Services.prefs.setBoolPref(PREF_TRIMURL, true);
   Services.prefs.setBoolPref(PREF_AUTOFILL, true);
 
   // Adding a tab would hit switch-to-tab, so it's safer to just add a visit.
-  yield PlacesTestUtils.addVisits({
+  yield PlacesTestUtils.addVisits([{
     uri: "http://www.autofilltrimurl.com/whatever",
     transition: Ci.nsINavHistoryService.TRANSITION_TYPED,
-  });
+  }, {
+    uri: "https://www.secureautofillurl.com/whatever",
+    transition: Ci.nsINavHistoryService.TRANSITION_TYPED,
+  }]);
 });
 
 function* promiseSearch(searchtext) {
   gURLBar.focus();
   gURLBar.inputField.value = searchtext.substr(0, searchtext.length - 1);
   EventUtils.synthesizeKey(searchtext.substr(-1, 1), {});
   yield promiseSearchComplete();
 }
 
-add_task(function* () {
-  yield promiseSearch("http://");
-  is(gURLBar.inputField.value, "http://", "Autofilled value is as expected");
+function* promiseTestResult(test) {
+  info("Searching for '${test.search}'");
+
+  yield promiseSearch(test.search);
+
+  is(gURLBar.inputField.value, test.autofilledValue,
+     `Autofilled value is as expected for search '${test.search}'`);
+
+  let result = gURLBar.popup.richlistbox.getItemAtIndex(0);
+
+  is(result._titleText.textContent, test.resultListDisplayTitle,
+     `Autocomplete result should have displayed title as expected for search '${test.search}'`);
+
+  is(result._actionText.textContent, test.resultListActionText,
+     `Autocomplete action text should be as expected for search '${test.search}'`);
+
+  is(result.getAttribute("type"), test.resultListType,
+     `Autocomplete result should have searchengine for the type for search '${test.search}'`);
+
+  is(gURLBar.mController.getFinalCompleteValueAt(0), test.finalCompleteValue,
+     `Autocomplete item should go to the expected final value for search '${test.search}'`);
+}
+
+const tests = [{
+    search: "http://",
+    autofilledValue: "http://",
+    resultListDisplayTitle: "http://",
+    resultListActionText: "Search with Google",
+    resultListType: "searchengine",
+    finalCompleteValue: 'moz-action:searchengine,{"engineName":"Google","input":"http%3A%2F%2F","searchQuery":"http%3A%2F%2F"}'
+  }, {
+    search: "https://",
+    autofilledValue: "https://",
+    resultListDisplayTitle: "https://",
+    resultListActionText: "Search with Google",
+    resultListType: "searchengine",
+    finalCompleteValue: 'moz-action:searchengine,{"engineName":"Google","input":"https%3A%2F%2F","searchQuery":"https%3A%2F%2F"}'
+  }, {
+    search: "au",
+    autofilledValue: "autofilltrimurl.com/",
+    resultListDisplayTitle: "www.autofilltrimurl.com",
+    resultListActionText: "Visit",
+    resultListType: "",
+    finalCompleteValue: "www.autofilltrimurl.com/"
+  }, {
+    search: "http://au",
+    autofilledValue: "http://autofilltrimurl.com/",
+    resultListDisplayTitle: "autofilltrimurl.com",
+    resultListActionText: "Visit",
+    resultListType: "",
+    finalCompleteValue: "http://autofilltrimurl.com/"
+  }, {
+    search: "sec",
+    autofilledValue: "secureautofillurl.com/",
+    resultListDisplayTitle: "https://www.secureautofillurl.com",
+    resultListActionText: "Visit",
+    resultListType: "",
+    finalCompleteValue: "https://www.secureautofillurl.com/"
+  }, {
+    search: "https://sec",
+    autofilledValue: "https://secureautofillurl.com/",
+    resultListDisplayTitle: "https://secureautofillurl.com",
+    resultListActionText: "Visit",
+    resultListType: "",
+    finalCompleteValue: "https://secureautofillurl.com/"
+  },
+];
+
+add_task(function* autofill_tests() {
+  for (let test of tests) {
+    yield promiseTestResult(test);
+  }
 });
 
-add_task(function* () {
-  yield promiseSearch("http://au");
-  is(gURLBar.inputField.value, "http://autofilltrimurl.com/", "Autofilled value is as expected");
-});
-
-add_task(function* () {
+add_task(function* autofill_complete_domain() {
   yield promiseSearch("http://www.autofilltrimurl.com");
   is(gURLBar.inputField.value, "http://www.autofilltrimurl.com/", "Autofilled value is as expected");
 
   // Now ensure selecting from the popup correctly trims.
   is(gURLBar.controller.matchCount, 2, "Found the expected number of matches");
   EventUtils.synthesizeKey("VK_DOWN", {});
   is(gURLBar.inputField.value, "www.autofilltrimurl.com/whatever", "trim was applied correctly");
 });
--- a/browser/base/content/test/urlbar/head.js
+++ b/browser/base/content/test/urlbar/head.js
@@ -1,8 +1,10 @@
+/* eslint-env mozilla/frame-script */
+
 Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
 
 XPCOMUtils.defineLazyModuleGetter(this, "Promise",
   "resource://gre/modules/Promise.jsm");
 XPCOMUtils.defineLazyModuleGetter(this, "Task",
   "resource://gre/modules/Task.jsm");
 XPCOMUtils.defineLazyModuleGetter(this, "PlacesUtils",
   "resource://gre/modules/PlacesUtils.jsm");
@@ -196,9 +198,8 @@ function promiseNewSearchEngine(basename
       },
       onError(errCode) {
         Assert.ok(false, "addEngine failed with error code " + errCode);
         reject();
       },
     });
   });
 }
-
--- a/browser/base/content/test/urlbar/urlbarAddonIframeContentScript.js
+++ b/browser/base/content/test/urlbar/urlbarAddonIframeContentScript.js
@@ -1,8 +1,10 @@
+/* eslint-env mozilla/frame-script */
+
 // Forward messages from the test to the iframe as events.
 addMessageListener("TestMessage", msg => {
   content.dispatchEvent(new content.CustomEvent("TestEvent", {
     detail: Components.utils.cloneInto(msg.data, content),
   }));
 });
 
 // Forward events from the iframe to the test as messages.
--- a/browser/base/content/test/webrtc/get_user_media_content_script.js
+++ b/browser/base/content/test/webrtc/get_user_media_content_script.js
@@ -1,11 +1,13 @@
 /* Any copyright is dedicated to the Public Domain.
  * http://creativecommons.org/publicdomain/zero/1.0/ */
 
+/* eslint-env mozilla/frame-script */
+
 Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
 XPCOMUtils.defineLazyServiceGetter(this, "MediaManagerService",
                                    "@mozilla.org/mediaManagerService;1",
                                    "nsIMediaManagerService");
 
 const kObservedTopics = [
   "getUserMedia:response:allow",
   "getUserMedia:revoke",
--- a/browser/components/safebrowsing/content/test/browser_bug400731.js
+++ b/browser/components/safebrowsing/content/test/browser_bug400731.js
@@ -1,10 +1,12 @@
 /* Check presence of the "Ignore this warning" button */
 
+/* eslint-env mozilla/frame-script */
+
 function onDOMContentLoaded(callback) {
   function complete({ data }) {
     mm.removeMessageListener("Test:DOMContentLoaded", complete);
     callback(data);
   }
 
   let mm = gBrowser.selectedBrowser.messageManager;
   mm.addMessageListener("Test:DOMContentLoaded", complete);
--- a/browser/components/uitour/content-UITour.js
+++ b/browser/components/uitour/content-UITour.js
@@ -1,12 +1,14 @@
 /* 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/. */
 
+/* eslint-env mozilla/frame-script */
+
 var {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
 
 const PREF_TEST_WHITELIST = "browser.uitour.testingOrigins";
 const UITOUR_PERMISSION   = "uitour";
 
 var UITourListener = {
   handleEvent(event) {
     if (!Services.prefs.getBoolPref("browser.uitour.enabled")) {
--- a/browser/extensions/webcompat-reporter/test/browser/browser_report_site_issue.js
+++ b/browser/extensions/webcompat-reporter/test/browser/browser_report_site_issue.js
@@ -1,13 +1,14 @@
 /* Test that clicking on the Report Site Issue button opens a new tab
-   and sends a postMessaged blob at it.
-   testing/profiles/prefs_general.js sets the value for
-   "extensions.webcompat-reporter.newIssueEndpoint" */
+   and sends a postMessaged blob to it. */
 add_task(function* test_screenshot() {
+  requestLongerTimeout(2);
+
+  // ./head.js sets the value for PREF_WC_REPORTER_ENDPOINT
   yield SpecialPowers.pushPrefEnv({set: [[PREF_WC_REPORTER_ENDPOINT, NEW_ISSUE_PAGE]]});
 
   let tab1 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, TEST_PAGE);
   yield PanelUI.show();
 
   let webcompatButton = document.getElementById("webcompat-reporter-button");
   ok(webcompatButton, "Report Site Issue button exists.");
 
--- a/browser/themes/linux/browser.css
+++ b/browser/themes/linux/browser.css
@@ -358,21 +358,17 @@ menuitem.bookmark-item {
 #bookmarks-menu-button[cui-areatype="toolbar"] > .toolbarbutton-menubutton-dropmarker > .dropmarker-icon {
   max-width: 18px;
 }
 
 .findbar-button,
 :-moz-any(#TabsToolbar, #nav-bar) .toolbarbutton-1 > .toolbarbutton-menubutton-button,
 :-moz-any(#TabsToolbar, #nav-bar) .toolbarbutton-1 {
   -moz-appearance: none;
-}
-
-:-moz-any(#TabsToolbar, #nav-bar) .toolbarbutton-1[open="true"],
-:-moz-any(#TabsToolbar, #nav-bar) .toolbarbutton-1:hover:active {
-  padding: 3px;
+  padding: 0 3px;
 }
 
 .findbar-button > .toolbarbutton-text,
 :-moz-any(#TabsToolbar, #nav-bar) .toolbarbutton-1 > .toolbarbutton-menubutton-button > .toolbarbutton-icon,
 :-moz-any(#TabsToolbar, #nav-bar) .toolbarbutton-1 > .toolbarbutton-menubutton-dropmarker > .dropmarker-icon,
 :-moz-any(#TabsToolbar, #nav-bar) .toolbarbutton-1 > .toolbarbutton-badge-stack,
 :-moz-any(#TabsToolbar, #nav-bar) .toolbarbutton-1 > .toolbarbutton-icon {
   margin-inline-end: 0;
@@ -431,22 +427,16 @@ menuitem.bookmark-item {
   transition-duration: 10ms;
 }
 
 :-moz-any(#TabsToolbar, #nav-bar) .toolbarbutton-1[checked]:not(:active):hover > .toolbarbutton-icon {
   background-color: var(--toolbarbutton-checkedhover-backgroundcolor);
   transition: background-color 150ms;
 }
 
-:-moz-any(#TabsToolbar, #nav-bar) .toolbarbutton-1 > .toolbarbutton-menubutton-button[open],
-:-moz-any(#TabsToolbar, #nav-bar) .toolbarbutton-1 > .toolbarbutton-menubutton-button:hover:active,
-:-moz-any(#TabsToolbar, #nav-bar) .toolbarbutton-1:hover:active {
-  padding: 3px;
-}
-
 :-moz-any(#TabsToolbar, #nav-bar) .toolbaritem-combined-buttons {
   margin-left: 2px;
   margin-right: 2px;
 }
 
 :-moz-any(#TabsToolbar, #nav-bar) .toolbaritem-combined-buttons > .toolbarbutton-1 {
   padding-left: 0;
   padding-right: 0;
--- a/browser/themes/windows/browser.css
+++ b/browser/themes/windows/browser.css
@@ -627,19 +627,17 @@ toolbar[brighttext] .toolbarbutton-1 > .
 }
 
 %include ../shared/menupanel.inc.css
 
 .findbar-button,
 #nav-bar .toolbarbutton-1,
 #nav-bar .toolbarbutton-1 > .toolbarbutton-menubutton-button {
   -moz-appearance: none;
-  border: none;
   padding: 0;
-  background: none;
 }
 
 #nav-bar .toolbarbutton-1:not([type=menu-button]),
 #nav-bar .toolbarbutton-1 > .toolbarbutton-menubutton-button,
 #nav-bar .toolbarbutton-1 > .toolbarbutton-menubutton-dropmarker {
   padding: var(--toolbarbutton-vertical-outer-padding) 2px;
   -moz-box-pack: center;
 }
--- a/build/moz.configure/warnings.configure
+++ b/build/moz.configure/warnings.configure
@@ -96,16 +96,19 @@ check_and_add_gcc_warning('-Wno-error=de
 check_and_add_gcc_warning('-Wno-error=array-bounds')
 
 # can't get rid of those PGO warnings
 check_and_add_gcc_warning('-Wno-error=coverage-mismatch', when='MOZ_PGO')
 
 # false positives during PGO
 check_and_add_gcc_warning('-Wno-error=free-nonheap-object', when='MOZ_PGO')
 
+# catches format/argument mismatches with printf
+check_and_add_gcc_warning('-Wformat')
+
 # We use mix of both POSIX and Win32 printf format across the tree, so format
 # warnings are useless on mingw.
 check_and_add_gcc_warning('-Wno-format',
                           when=depends(target)(lambda t: t.kernel == 'WINNT'))
 
 # Please keep these last in this file
 add_old_configure_assignment('_WARNINGS_CFLAGS', warnings_cflags)
 add_old_configure_assignment('_WARNINGS_CXXFLAGS', warnings_cxxflags)
--- a/chrome/nsChromeRegistry.cpp
+++ b/chrome/nsChromeRegistry.cpp
@@ -3,18 +3,16 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "nsChromeRegistry.h"
 #include "nsChromeRegistryChrome.h"
 #include "nsChromeRegistryContent.h"
 
-#include "prprf.h"
-
 #include "nsCOMPtr.h"
 #include "nsError.h"
 #include "nsEscape.h"
 #include "nsNetUtil.h"
 #include "nsString.h"
 #include "nsQueryObject.h"
 
 #include "mozilla/dom/URL.h"
@@ -24,16 +22,17 @@
 #include "nsIDOMLocation.h"
 #include "nsIDOMWindowCollection.h"
 #include "nsIDOMWindow.h"
 #include "nsIObserverService.h"
 #include "nsIPresShell.h"
 #include "nsIScriptError.h"
 #include "nsIWindowMediator.h"
 #include "nsIPrefService.h"
+#include "mozilla/Printf.h"
 #include "mozilla/StyleSheet.h"
 #include "mozilla/StyleSheetInlines.h"
 
 #ifdef ENABLE_INTL_API
 #include "unicode/uloc.h"
 #endif
 
 nsChromeRegistry* nsChromeRegistry::gChromeRegistry;
@@ -50,23 +49,23 @@ nsChromeRegistry::LogMessage(const char*
 {
   nsCOMPtr<nsIConsoleService> console 
     (do_GetService(NS_CONSOLESERVICE_CONTRACTID));
   if (!console)
     return;
 
   va_list args;
   va_start(args, aMsg);
-  char* formatted = PR_vsmprintf(aMsg, args);
+  char* formatted = mozilla::Vsmprintf(aMsg, args);
   va_end(args);
   if (!formatted)
     return;
 
   console->LogStringMessage(NS_ConvertUTF8toUTF16(formatted).get());
-  PR_smprintf_free(formatted);
+  mozilla::SmprintfFree(formatted);
 }
 
 void
 nsChromeRegistry::LogMessageWithContext(nsIURI* aURL, uint32_t aLineNumber, uint32_t flags,
                                         const char* aMsg, ...)
 {
   nsresult rv;
 
@@ -75,30 +74,30 @@ nsChromeRegistry::LogMessageWithContext(
 
   nsCOMPtr<nsIScriptError> error
     (do_CreateInstance(NS_SCRIPTERROR_CONTRACTID));
   if (!console || !error)
     return;
 
   va_list args;
   va_start(args, aMsg);
-  char* formatted = PR_vsmprintf(aMsg, args);
+  char* formatted = mozilla::Vsmprintf(aMsg, args);
   va_end(args);
   if (!formatted)
     return;
 
   nsCString spec;
   if (aURL)
     aURL->GetSpec(spec);
 
   rv = error->Init(NS_ConvertUTF8toUTF16(formatted),
                    NS_ConvertUTF8toUTF16(spec),
                    EmptyString(),
                    aLineNumber, 0, flags, "chrome registration");
-  PR_smprintf_free(formatted);
+  mozilla::SmprintfFree(formatted);
 
   if (NS_FAILED(rv))
     return;
 
   console->LogMessage(error);
 }
 
 nsChromeRegistry::~nsChromeRegistry()
--- a/chrome/nsChromeRegistry.h
+++ b/chrome/nsChromeRegistry.h
@@ -78,19 +78,21 @@ protected:
 
   void FlushSkinCaches();
   void FlushAllCaches();
 
   // Update the selected locale used by the chrome registry, and fire a
   // notification about this change
   virtual nsresult UpdateSelectedLocale() = 0;
 
-  static void LogMessage(const char* aMsg, ...);
+  static void LogMessage(const char* aMsg, ...)
+    MOZ_FORMAT_PRINTF(1, 2);
   static void LogMessageWithContext(nsIURI* aURL, uint32_t aLineNumber, uint32_t flags,
-                                    const char* aMsg, ...);
+                                    const char* aMsg, ...)
+    MOZ_FORMAT_PRINTF(4, 5);
 
   virtual nsIURI* GetBaseURIFromPackage(const nsCString& aPackage,
                                         const nsCString& aProvider,
                                         const nsCString& aPath) = 0;
   virtual nsresult GetFlagsFromPackage(const nsCString& aPackage,
                                        uint32_t* aFlags) = 0;
 
   nsresult SelectLocaleFromPref(nsIPrefBranch* prefs);
--- a/devtools/client/inspector/layout/components/GridList.js
+++ b/devtools/client/inspector/layout/components/GridList.js
@@ -36,17 +36,17 @@ module.exports = createClass({
     } = this.props;
 
     return dom.div(
       {
         className: "grid-container",
       },
       dom.span(
         {},
-        getStr("layout.overlayMultipleGrids")
+        getStr("layout.overlayGrid")
       ),
       dom.ul(
         {},
         grids.map(grid => {
           let { nodeFront } = grid;
           let { displayName, attributes } = nodeFront;
 
           let gridName = displayName;
--- a/devtools/client/locales/en-US/layout.properties
+++ b/devtools/client/locales/en-US/layout.properties
@@ -24,8 +24,12 @@ layout.gridDisplaySettings=Grid Display 
 
 # LOCALIZATION NOTE (layout.noGrids): In the case where there are no CSS grid
 # containers to display.
 layout.noGrids=No grids
 
 # LOCALIZATION NOTE (layout.overlayMultipleGrids): The header for the list of grid
 # container elements that can be highlighted in the CSS Grid pane.
 layout.overlayMultipleGrids=Overlay Multiple Grids
+
+# LOCALIZATION NOTE (layout.overlayGrid): Alternate header for the list of grid container
+# elements if only one item can be selected.
+layout.overlayGrid=Overlay Grid
--- a/devtools/client/netmonitor/har/har-automation.js
+++ b/devtools/client/netmonitor/har/har-automation.js
@@ -3,17 +3,16 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 /* eslint-disable mozilla/reject-some-requires */
 
 "use strict";
 
 const { Ci } = require("chrome");
 const { Class } = require("sdk/core/heritage");
-const { resolve } = require("promise");
 const Services = require("Services");
 
 loader.lazyRequireGetter(this, "HarCollector", "devtools/client/netmonitor/har/har-collector", true);
 loader.lazyRequireGetter(this, "HarExporter", "devtools/client/netmonitor/har/har-exporter", true);
 loader.lazyRequireGetter(this, "HarUtils", "devtools/client/netmonitor/har/har-utils", true);
 
 const prefDomain = "devtools.netmonitor.har.";
 
@@ -117,17 +116,17 @@ var HarAutomation = Class({
     }
   },
 
   autoExport: function () {
     let autoExport = Services.prefs.getBoolPref(prefDomain +
       "enableAutoExportToFile");
 
     if (!autoExport) {
-      return resolve();
+      return Promise.resolve();
     }
 
     // Auto export to file is enabled, so save collected data
     // into a file and use all the default options.
     let data = {
       fileName: Services.prefs.getCharPref(prefDomain + "defaultFileName"),
     };
 
--- a/devtools/client/netmonitor/har/har-builder.js
+++ b/devtools/client/netmonitor/har/har-builder.js
@@ -1,29 +1,25 @@
 /* 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/. */
 
 "use strict";
 
-const { defer, all } = require("promise");
-const { LocalizationHelper } = require("devtools/shared/l10n");
 const Services = require("Services");
 const appInfo = Services.appinfo;
+const { LocalizationHelper } = require("devtools/shared/l10n");
 const { CurlUtils } = require("devtools/client/shared/curl");
 const {
   getFormDataSections,
   getUrlQuery,
   parseQueryString,
 } = require("devtools/client/netmonitor/request-utils");
 
-loader.lazyGetter(this, "L10N", () => {
-  return new LocalizationHelper("devtools/client/locales/har.properties");
-});
-
+const L10N = new LocalizationHelper("devtools/client/locales/har.properties");
 const HAR_VERSION = "1.1";
 
 /**
  * This object is responsible for building HAR file. See HAR spec:
  * https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/HAR/Overview.html
  * http://www.softwareishard.com/blog/har-12-spec/
  *
  * @param {Object} options configuration object
@@ -63,20 +59,17 @@ HarBuilder.prototype = {
 
     // Build entries.
     for (let file of this._options.items) {
       log.entries.push(this.buildEntry(log, file));
     }
 
     // Some data needs to be fetched from the backend during the
     // build process, so wait till all is done.
-    let { resolve, promise } = defer();
-    all(this.promises).then(results => resolve({ log: log }));
-
-    return promise;
+    return Promise.all(this.promises).then(() => ({ log }));
   },
 
   // Helpers
 
   buildLog: function () {
     return {
       version: HAR_VERSION,
       creator: {
--- a/devtools/client/netmonitor/har/har-collector.js
+++ b/devtools/client/netmonitor/har/har-collector.js
@@ -1,16 +1,14 @@
 /* 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/. */
 
 "use strict";
 
-const { defer, all } = require("promise");
-const { makeInfallible } = require("devtools/shared/DevToolsUtils");
 const Services = require("Services");
 
 // Helper tracer. Should be generic sharable by other modules (bug 1171927)
 const trace = {
   log: function (...args) {
   }
 };
 
@@ -27,18 +25,16 @@ function HarCollector(options) {
   this.onRequestHeaders = this.onRequestHeaders.bind(this);
   this.onRequestCookies = this.onRequestCookies.bind(this);
   this.onRequestPostData = this.onRequestPostData.bind(this);
   this.onResponseHeaders = this.onResponseHeaders.bind(this);
   this.onResponseCookies = this.onResponseCookies.bind(this);
   this.onResponseContent = this.onResponseContent.bind(this);
   this.onEventTimings = this.onEventTimings.bind(this);
 
-  this.onPageLoadTimeout = this.onPageLoadTimeout.bind(this);
-
   this.clear();
 }
 
 HarCollector.prototype = {
   // Connection
 
   start: function () {
     this.debuggerClient.addListener("networkEvent", this.onNetworkEvent);
@@ -61,23 +57,22 @@ HarCollector.prototype = {
     this.lastRequestStart = -1;
     this.requests = [];
   },
 
   waitForHarLoad: function () {
     // There should be yet another timeout e.g.:
     // 'devtools.netmonitor.har.pageLoadTimeout'
     // that should force export even if page isn't fully loaded.
-    let deferred = defer();
-    this.waitForResponses().then(() => {
-      trace.log("HarCollector.waitForHarLoad; DONE HAR loaded!");
-      deferred.resolve(this);
+    return new Promise((resolve) => {
+      this.waitForResponses().then(() => {
+        trace.log("HarCollector.waitForHarLoad; DONE HAR loaded!");
+        resolve(this);
+      });
     });
-
-    return deferred.promise;
   },
 
   waitForResponses: function () {
     trace.log("HarCollector.waitForResponses; " + this.requests.length);
 
     // All requests for additional data must be received to have complete
     // HTTP info to generate the result HAR file. So, wait for all current
     // promises. Note that new promises (requests) can be generated during the
@@ -112,33 +107,25 @@ HarCollector.prototype = {
     // The auto-export is not done if the timeout is set to zero (or less).
     // This is useful in cases where the export is done manually through
     // API exposed to the content.
     let timeout = Services.prefs.getIntPref(
       "devtools.netmonitor.har.pageLoadedTimeout");
 
     trace.log("HarCollector.waitForTimeout; " + timeout);
 
-    this.pageLoadDeferred = defer();
-
-    if (timeout <= 0) {
-      this.pageLoadDeferred.resolve();
-      return this.pageLoadDeferred.promise;
-    }
-
-    this.pageLoadTimeout = setTimeout(this.onPageLoadTimeout, timeout);
-
-    return this.pageLoadDeferred.promise;
-  },
-
-  onPageLoadTimeout: function () {
-    trace.log("HarCollector.onPageLoadTimeout;");
-
-    // Ha, page has been loaded. Resolve the final timeout promise.
-    this.pageLoadDeferred.resolve();
+    return new Promise((resolve) => {
+      if (timeout <= 0) {
+        resolve();
+      }
+      this.pageLoadTimeout = setTimeout(() => {
+        trace.log("HarCollector.onPageLoadTimeout;");
+        resolve();
+      }, timeout);
+    });
   },
 
   resetPageLoadTimeout: function () {
     // Remove the current timeout.
     if (this.pageLoadTimeout) {
       trace.log("HarCollector.resetPageLoadTimeout;");
 
       clearTimeout(this.pageLoadTimeout);
@@ -268,38 +255,34 @@ HarCollector.prototype = {
     if (request) {
       this.requests.push(request);
     }
 
     this.resetPageLoadTimeout();
   },
 
   getData: function (actor, method, callback) {
-    let deferred = defer();
+    return new Promise((resolve) => {
+      if (!this.webConsoleClient[method]) {
+        console.error("HarCollector.getData: ERROR Unknown method!");
+        resolve();
+      }
 
-    if (!this.webConsoleClient[method]) {
-      console.error("HarCollector.getData; ERROR " +
-                    "Unknown method!");
-      return deferred.resolve();
-    }
-
-    let file = this.getFile(actor);
+      let file = this.getFile(actor);
 
-    trace.log("HarCollector.getData; REQUEST " + method +
-      ", " + file.url, file);
+      trace.log("HarCollector.getData; REQUEST " + method +
+        ", " + file.url, file);
 
-    this.webConsoleClient[method](actor, response => {
-      trace.log("HarCollector.getData; RESPONSE " + method +
-        ", " + file.url, response);
-
-      callback(response);
-      deferred.resolve(response);
+      this.webConsoleClient[method](actor, response => {
+        trace.log("HarCollector.getData; RESPONSE " + method +
+          ", " + file.url, response);
+        callback(response);
+        resolve(response);
+      });
     });
-
-    return deferred.promise;
   },
 
   /**
    * Handles additional information received for a "requestHeaders" packet.
    *
    * @param object response
    *        The message received from the server.
    */
@@ -401,25 +384,29 @@ HarCollector.prototype = {
 
     let totalTime = response.totalTime;
     file.totalTime = totalTime;
     file.endedMillis = file.startedMillis + totalTime;
   },
 
   // Helpers
 
-  getLongHeaders: makeInfallible(function (headers) {
+  getLongHeaders: function (headers) {
     for (let header of headers) {
       if (typeof header.value == "object") {
-        this.getString(header.value).then(value => {
-          header.value = value;
-        });
+        try {
+          this.getString(header.value).then(value => {
+            header.value = value;
+          });
+        } catch (error) {
+          trace.log("HarCollector.getLongHeaders; ERROR when getString", error);
+        }
       }
     }
-  }),
+  },
 
   /**
    * Fetches the full text of a string.
    *
    * @param object | string stringGrip
    *        The long string grip containing the corresponding actor.
    *        If you pass in a plain string (by accident or because you're lazy),
    *        then a promise of the same string is simply returned.
@@ -442,17 +429,17 @@ HarCollector.prototype = {
  * The function will wait even for the newly added promises.
  * (this isn't possible with the default Promise.all);
  */
 function waitForAll(promises) {
   // Remove all from the original array and get clone of it.
   let clone = promises.splice(0, promises.length);
 
   // Wait for all promises in the given array.
-  return all(clone).then(() => {
+  return Promise.all(clone).then(() => {
     // If there are new promises (in the original array)
     // to wait for - chain them!
     if (promises.length) {
       return waitForAll(promises);
     }
     return undefined;
   });
 }
--- a/devtools/client/netmonitor/har/har-exporter.js
+++ b/devtools/client/netmonitor/har/har-exporter.js
@@ -1,28 +1,19 @@
 /* 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/. */
 
-/* eslint-disable mozilla/reject-some-requires */
-
 "use strict";
 
-const { Cc, Ci } = require("chrome");
 const Services = require("Services");
-const { XPCOMUtils } = require("resource://gre/modules/XPCOMUtils.jsm");
-const { resolve } = require("promise");
+const clipboardHelper = require("devtools/shared/platform/clipboard");
 const { HarUtils } = require("./har-utils.js");
 const { HarBuilder } = require("./har-builder.js");
 
-XPCOMUtils.defineLazyGetter(this, "clipboardHelper", function () {
-  return Cc["@mozilla.org/widget/clipboardhelper;1"]
-    .getService(Ci.nsIClipboardHelper);
-});
-
 var uid = 1;
 
 // Helper tracer. Should be generic sharable by other modules (bug 1171927)
 const trace = {
   log: function (...args) {
   }
 };
 
@@ -78,17 +69,17 @@ const HarExporter = {
       "devtools.netmonitor.har.compress");
 
     // Get target file for exported data. Bail out, if the user
     // presses cancel.
     let file = HarUtils.getTargetFile(options.defaultFileName,
       options.jsonp, options.compress);
 
     if (!file) {
-      return resolve();
+      return Promise.resolve();
     }
 
     trace.log("HarExporter.save; " + options.defaultFileName, options);
 
     return this.fetchHarData(options).then(jsonString => {
       if (!HarUtils.saveToFile(file, jsonString, options.compress)) {
         let msg = "Failed to save HAR file at: " + options.defaultFileName;
         console.error(msg);
@@ -127,22 +118,22 @@ const HarExporter = {
     options.forceExport = options.forceExport ||
       Services.prefs.getBoolPref("devtools.netmonitor.har.forceExport");
 
     // Build HAR object.
     return this.buildHarData(options).then(har => {
       // Do not export an empty HAR file, unless the user
       // explicitly says so (using the forceExport option).
       if (!har.log.entries.length && !options.forceExport) {
-        return resolve();
+        return Promise.resolve();
       }
 
       let jsonString = this.stringify(har);
       if (!jsonString) {
-        return resolve();
+        return Promise.resolve();
       }
 
       // If JSONP is wanted, wrap the string in a function call
       if (options.jsonp) {
         // This callback name is also used in HAR Viewer by default.
         // http://www.softwareishard.com/har/viewer/
         let callbackName = options.jsonpCallback || "onInputData";
         jsonString = callbackName + "(" + jsonString + ");";
--- a/devtools/client/netmonitor/netmonitor-controller.js
+++ b/devtools/client/netmonitor/netmonitor-controller.js
@@ -1,15 +1,14 @@
 /* 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/. */
 
 "use strict";
 
-const promise = require("promise");
 const Services = require("Services");
 const EventEmitter = require("devtools/shared/event-emitter");
 const { TimelineFront } = require("devtools/shared/fronts/timeline");
 const { CurlUtils } = require("devtools/client/shared/curl");
 const { ACTIVITY_TYPE } = require("./constants");
 const { EVENTS } = require("./events");
 const { configureStore } = require("./store");
 const Actions = require("./actions/index");
@@ -29,119 +28,122 @@ const gStore = window.gStore = configure
  */
 var NetMonitorController = {
   /**
    * Initializes the view and connects the monitor client.
    *
    * @return object
    *         A promise that is resolved when the monitor finishes startup.
    */
-  async startupNetMonitor() {
+  startupNetMonitor() {
     if (this._startup) {
-      return this._startup.promise;
+      return this._startup;
     }
-    this._startup = promise.defer();
-    await this.connect();
-    this._startup.resolve();
-    return undefined;
+    this._startup = new Promise(async (resolve) => {
+      await this.connect();
+      resolve();
+    });
+    return this._startup;
   },
 
   /**
    * Destroys the view and disconnects the monitor client from the server.
    *
    * @return object
    *         A promise that is resolved when the monitor finishes shutdown.
    */
-  async shutdownNetMonitor() {
+  shutdownNetMonitor() {
     if (this._shutdown) {
-      return this._shutdown.promise;
+      return this._shutdown;
     }
-    this._shutdown = promise.defer();
-    gStore.dispatch(Actions.batchReset());
-    this.TargetEventsHandler.disconnect();
-    this.NetworkEventsHandler.disconnect();
-    await this.disconnect();
-    this._shutdown.resolve();
-    return undefined;
+    this._shutdown = new Promise(async (resolve) => {
+      gStore.dispatch(Actions.batchReset());
+      this.TargetEventsHandler.disconnect();
+      this.NetworkEventsHandler.disconnect();
+      await this.disconnect();
+      resolve();
+    });
+
+    return this._shutdown;
   },
 
   /**
    * Initiates remote or chrome network monitoring based on the current target,
    * wiring event handlers as necessary. Since the TabTarget will have already
    * started listening to network requests by now, this is largely
    * netmonitor-specific initialization.
    *
    * @return object
    *         A promise that is resolved when the monitor finishes connecting.
    */
-  async connect() {
+  connect() {
     if (this._connection) {
-      return this._connection.promise;
+      return this._connection;
     }
-    this._connection = promise.defer();
-
-    // Some actors like AddonActor or RootActor for chrome debugging
-    // aren't actual tabs.
-    if (this._target.isTabActor) {
-      this.tabClient = this._target.activeTab;
-    }
+    this._connection = new Promise(async (resolve) => {
+      // Some actors like AddonActor or RootActor for chrome debugging
+      // aren't actual tabs.
+      if (this._target.isTabActor) {
+        this.tabClient = this._target.activeTab;
+      }
 
-    let connectTimeline = () => {
-      // Don't start up waiting for timeline markers if the server isn't
-      // recent enough to emit the markers we're interested in.
-      if (this._target.getTrait("documentLoadingMarkers")) {
-        this.timelineFront = new TimelineFront(this._target.client,
-          this._target.form);
-        return this.timelineFront.start({ withDocLoadingEvents: true });
-      }
-      return undefined;
-    };
+      let connectTimeline = () => {
+        // Don't start up waiting for timeline markers if the server isn't
+        // recent enough to emit the markers we're interested in.
+        if (this._target.getTrait("documentLoadingMarkers")) {
+          this.timelineFront = new TimelineFront(this._target.client,
+            this._target.form);
+          return this.timelineFront.start({ withDocLoadingEvents: true });
+        }
+        return undefined;
+      };
 
-    this.webConsoleClient = this._target.activeConsole;
-    await connectTimeline();
+      this.webConsoleClient = this._target.activeConsole;
+      await connectTimeline();
 
-    this.TargetEventsHandler.connect();
-    this.NetworkEventsHandler.connect();
+      this.TargetEventsHandler.connect();
+      this.NetworkEventsHandler.connect();
 
-    window.emit(EVENTS.CONNECTED);
+      window.emit(EVENTS.CONNECTED);
 
-    this._connection.resolve();
-    this._connected = true;
-    return undefined;
+      resolve();
+      this._connected = true;
+    });
+    return this._connection;
   },
 
   /**
    * Disconnects the debugger client and removes event handlers as necessary.
    */
-  async disconnect() {
+  disconnect() {
     if (this._disconnection) {
-      return this._disconnection.promise;
+      return this._disconnection;
     }
-    this._disconnection = promise.defer();
-
-    // Wait for the connection to finish first.
-    if (!this.isConnected()) {
-      await this._connection.promise;
-    }
+    this._disconnection = new Promise(async (resolve) => {
+      // Wait for the connection to finish first.
+      if (!this.isConnected()) {
+        await this._connection;
+      }
 
-    // When debugging local or a remote instance, the connection is closed by
-    // the RemoteTarget. The webconsole actor is stopped on disconnect.
-    this.tabClient = null;
-    this.webConsoleClient = null;
+      // When debugging local or a remote instance, the connection is closed by
+      // the RemoteTarget. The webconsole actor is stopped on disconnect.
+      this.tabClient = null;
+      this.webConsoleClient = null;
 
-    // The timeline front wasn't initialized and started if the server wasn't
-    // recent enough to emit the markers we were interested in.
-    if (this._target.getTrait("documentLoadingMarkers")) {
-      await this.timelineFront.destroy();
-      this.timelineFront = null;
-    }
+      // The timeline front wasn't initialized and started if the server wasn't
+      // recent enough to emit the markers we were interested in.
+      if (this._target.getTrait("documentLoadingMarkers")) {
+        await this.timelineFront.destroy();
+        this.timelineFront = null;
+      }
 
-    this._disconnection.resolve();
-    this._connected = false;
-    return undefined;
+      resolve();
+      this._connected = false;
+    });
+    return this._disconnection;
   },
 
   /**
    * Checks whether the netmonitor connection is active.
    * @return boolean
    */
   isConnected: function () {
     return !!this._connected;
@@ -168,30 +170,30 @@ var NetMonitorController = {
   triggerActivity: function (type) {
     // Puts the frontend into "standby" (when there's no particular activity).
     let standBy = () => {
       this._currentActivity = ACTIVITY_TYPE.NONE;
     };
 
     // Waits for a series of "navigation start" and "navigation stop" events.
     let waitForNavigation = () => {
-      let deferred = promise.defer();
-      this._target.once("will-navigate", () => {
-        this._target.once("navigate", () => {
-          deferred.resolve();
+      return new Promise((resolve) => {
+        this._target.once("will-navigate", () => {
+          this._target.once("navigate", () => {
+            resolve();
+          });
         });
       });
-      return deferred.promise;
     };
 
     // Reconfigures the tab, optionally triggering a reload.
     let reconfigureTab = options => {
-      let deferred = promise.defer();
-      this._target.activeTab.reconfigure(options, deferred.resolve);
-      return deferred.promise;
+      return new Promise((resolve) => {
+        this._target.activeTab.reconfigure(options, resolve);
+      });
     };
 
     // Reconfigures the tab and waits for the target to finish navigating.
     let reconfigureTabAndWaitForNavigation = options => {
       options.performReload = true;
       let navigationFinished = waitForNavigation();
       return reconfigureTab(options).then(() => navigationFinished);
     };
@@ -228,54 +230,54 @@ var NetMonitorController = {
     if (type == ACTIVITY_TYPE.DISABLE_CACHE) {
       this._currentActivity = type;
       return reconfigureTab({
         cacheDisabled: true,
         performReload: false
       }).then(standBy);
     }
     this._currentActivity = ACTIVITY_TYPE.NONE;
-    return promise.reject(new Error("Invalid activity type"));
+    return Promise.reject(new Error("Invalid activity type"));
   },
 
   /**
    * Selects the specified request in the waterfall and opens the details view.
    *
    * @param string requestId
    *        The actor ID of the request to inspect.
    * @return object
    *         A promise resolved once the task finishes.
    */
   inspectRequest: function (requestId) {
     // Look for the request in the existing ones or wait for it to appear, if
     // the network monitor is still loading.
-    let deferred = promise.defer();
-    let request = null;
-    let inspector = function () {
-      request = getDisplayedRequestById(gStore.getState(), requestId);
-      if (!request) {
-        // Reset filters so that the request is visible.
-        gStore.dispatch(Actions.toggleRequestFilterType("all"));
+    return new Promise((resolve) => {
+      let request = null;
+      let inspector = function () {
         request = getDisplayedRequestById(gStore.getState(), requestId);
-      }
+        if (!request) {
+          // Reset filters so that the request is visible.
+          gStore.dispatch(Actions.toggleRequestFilterType("all"));
+          request = getDisplayedRequestById(gStore.getState(), requestId);
+        }
 
-      // If the request was found, select it. Otherwise this function will be
-      // called again once new requests arrive.
-      if (request) {
-        window.off(EVENTS.REQUEST_ADDED, inspector);
-        gStore.dispatch(Actions.selectRequest(request.id));
-        deferred.resolve();
+        // If the request was found, select it. Otherwise this function will be
+        // called again once new requests arrive.
+        if (request) {
+          window.off(EVENTS.REQUEST_ADDED, inspector);
+          gStore.dispatch(Actions.selectRequest(request.id));
+          resolve();
+        }
+      };
+
+      inspector();
+      if (!request) {
+        window.on(EVENTS.REQUEST_ADDED, inspector);
       }
-    };
-
-    inspector();
-    if (!request) {
-      window.on(EVENTS.REQUEST_ADDED, inspector);
-    }
-    return deferred.promise;
+    });
   },
 
   /**
    * Getter that tells if the server supports sending custom network requests.
    * @type boolean
    */
   get supportsCustomRequest() {
     return this.webConsoleClient &&
--- a/devtools/client/netmonitor/request-list-context-menu.js
+++ b/devtools/client/netmonitor/request-list-context-menu.js
@@ -4,34 +4,30 @@
 
 "use strict";
 
 const Services = require("Services");
 const { Curl } = require("devtools/client/shared/curl");
 const { gDevTools } = require("devtools/client/framework/devtools");
 const Menu = require("devtools/client/framework/menu");
 const MenuItem = require("devtools/client/framework/menu-item");
+const clipboardHelper = require("devtools/shared/platform/clipboard");
+const { HarExporter } = require("./har/har-exporter");
 const { L10N } = require("./l10n");
 const {
   formDataURI,
   getFormDataSections,
   getUrlQuery,
   parseQueryString,
 } = require("./request-utils");
 const {
   getSelectedRequest,
   getSortedRequests,
 } = require("./selectors/index");
 
-loader.lazyRequireGetter(this, "HarExporter",
-  "devtools/client/netmonitor/har/har-exporter", true);
-
-loader.lazyServiceGetter(this, "clipboardHelper",
-  "@mozilla.org/widget/clipboardhelper;1", "nsIClipboardHelper");
-
 function RequestListContextMenu({
   cloneSelectedRequest,
   openStatistics,
 }) {
   this.cloneSelectedRequest = cloneSelectedRequest;
   this.openStatistics = openStatistics;
 }
 
--- a/devtools/client/webconsole/utils.js
+++ b/devtools/client/webconsole/utils.js
@@ -1,32 +1,32 @@
 /* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
 /* vim: set ft= javascript ts=2 et sw=2 tw=80: */
 /* 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/. */
 
 "use strict";
 
-const {Cc, Ci, Cu, components} = require("chrome");
+const {Cc, Ci} = require("chrome");
 const Services = require("Services");
 const {LocalizationHelper} = require("devtools/shared/l10n");
 
 // Match the function name from the result of toString() or toSource().
 //
 // Examples:
 // (function foobar(a, b) { ...
 // function foobar2(a) { ...
 // function() { ...
 const REGEX_MATCH_FUNCTION_NAME = /^\(?function\s+([^(\s]+)\s*\(/;
 
 // Number of terminal entries for the self-xss prevention to go away
 const CONSOLE_ENTRY_THRESHOLD = 5;
 
-const CONSOLE_WORKER_IDS = exports.CONSOLE_WORKER_IDS = [
+exports.CONSOLE_WORKER_IDS = [
   "SharedWorker",
   "ServiceWorker",
   "Worker"
 ];
 
 var WebConsoleUtils = {
 
   /**
@@ -99,62 +99,16 @@ var WebConsoleUtils = {
     let style = win.getComputedStyle(from);
     to.style.fontFamily = style.getPropertyCSSValue("font-family").cssText;
     to.style.fontSize = style.getPropertyCSSValue("font-size").cssText;
     to.style.fontWeight = style.getPropertyCSSValue("font-weight").cssText;
     to.style.fontStyle = style.getPropertyCSSValue("font-style").cssText;
   },
 
   /**
-   * Create a grip for the given value. If the value is an object,
-   * an object wrapper will be created.
-   *
-   * @param mixed value
-   *        The value you want to create a grip for, before sending it to the
-   *        client.
-   * @param function objectWrapper
-   *        If the value is an object then the objectWrapper function is
-   *        invoked to give us an object grip. See this.getObjectGrip().
-   * @return mixed
-   *         The value grip.
-   */
-  createValueGrip: function (value, objectWrapper) {
-    switch (typeof value) {
-      case "boolean":
-        return value;
-      case "string":
-        return objectWrapper(value);
-      case "number":
-        if (value === Infinity) {
-          return { type: "Infinity" };
-        } else if (value === -Infinity) {
-          return { type: "-Infinity" };
-        } else if (Number.isNaN(value)) {
-          return { type: "NaN" };
-        } else if (!value && 1 / value === -Infinity) {
-          return { type: "-0" };
-        }
-        return value;
-      case "undefined":
-        return { type: "undefined" };
-      case "object":
-        if (value === null) {
-          return { type: "null" };
-        }
-        // Fall through.
-      case "function":
-        return objectWrapper(value);
-      default:
-        console.error("Failed to provide a grip for value of " + typeof value
-                      + ": " + value);
-        return null;
-    }
-  },
-
-  /**
    * Determine if the given request mixes HTTP with HTTPS content.
    *
    * @param string request
    *        Location of the requested content.
    * @param string location
    *        Location of the current page.
    * @return boolean
    *         True if the content is mixed, false if not.
new file mode 100644
--- /dev/null
+++ b/docshell/test/navigation/file_bug386782_contenteditable.html
@@ -0,0 +1,1 @@
+<html><head><meta charset="utf-8"><script>window.addEventListener("pageshow", function(event) { window.opener.postMessage({persisted:event.persisted}, "*"); });</script></head><body contentEditable="true"><p>contentEditable</p></body></html>
\ No newline at end of file
new file mode 100644
--- /dev/null
+++ b/docshell/test/navigation/file_bug386782_designmode.html
@@ -0,0 +1,1 @@
+<html><head><meta charset="utf-8"><script>window.addEventListener("pageshow", function(event) { window.opener.postMessage({persisted:event.persisted}, "*"); });</script></head><body><p>designModeDocument</p></body></html>
\ No newline at end of file
--- a/docshell/test/navigation/mochitest.ini
+++ b/docshell/test/navigation/mochitest.ini
@@ -1,12 +1,14 @@
 [DEFAULT]
 support-files =
   NavigationUtils.js
   blank.html
+  file_bug386782_contenteditable.html
+  file_bug386782_designmode.html
   file_bug462076_1.html
   file_bug462076_2.html
   file_bug462076_3.html
   file_bug508537_1.html
   file_bug534178.html
   file_document_write_1.html
   file_fragment_handling_during_load.html
   file_nested_frames.html
--- a/docshell/test/navigation/test_bug386782.html
+++ b/docshell/test/navigation/test_bug386782.html
@@ -3,55 +3,50 @@
 <!--
 https://bugzilla.mozilla.org/show_bug.cgi?id=386782
 -->
 <head>
   <title>Test for Bug 386782</title>
   <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
   <script type="text/javascript" src="/tests/SimpleTest/EventUtils.js"></script>
   <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-  
+
   <script>
 
     // This tests if we can load a document whose root is in designMode,
     // edit it, navigate to a new page, navigate back, still edit, and still
     // undo/redo. Note that this is different from the case where the
     // designMode document is in a frame inside the window, as this means
-    // the editable region is not in the root docshell (a less complicated case).  
+    // the editable region is not in the root docshell (a less complicated case).
 
-    var pageShowChecker = '<scr' + 'ipt>' +
-      'window.addEventListener("pageshow", function(event) {' +
-        'window.opener.postMessage({persisted:event.persisted}, "*");' +
-      '});</scr' + 'ipt>';
-  
     var gTests = [
       {
         // <html><body><p>designModeDocument</p></body></html>
-        url: "data:text/html;charset=utf-8,<html><head>" + pageShowChecker + "</head><body><p>designModeDocument</p></body></html>",
+        url: "file_bug386782_designmode.html",
         name: 'designModeNavigate',
         onload(doc) { doc.designMode = "on"; },
         expectedBodyBeforeEdit: '<p>designModeDocument</p>',
         expectedBodyAfterEdit:  '<p>EDITED designModeDocument</p>',
         expectedBodyAfterSecondEdit: '<p>EDITED TWICE designModeDocument</p>',
       },
       {
         // <html><body contentEditable="true"><p>contentEditable</p></body></html>
-        url: "data:text/html;charset=utf-8,<html><head>" + pageShowChecker + "</head><body contentEditable=\"true\"><p>contentEditable</p></body></html>",
+        url: "file_bug386782_contenteditable.html",
         name: 'contentEditableNavigate',
         expectedBodyBeforeEdit: '<p>contentEditable</p>',
         expectedBodyAfterEdit:  'EDITED <br><p>contentEditable</p>',
         expectedBodyAfterSecondEdit: 'EDITED TWICE <br><p>contentEditable</p>',
       }
     ];
-    
+
     var gTestNum = -1;
     var gTest = null;
-    
+
     window.onload = goNext();
- 
+
     function goNext() {
       gTestNum++;
       if (gTestNum >= gTests.length) {
         SimpleTest.finish();
         return;
       }
       gTest = gTests[gTestNum];
       gTest.window = window.open(gTest.url, gTest.name, "width=500,height=500");
@@ -69,20 +64,20 @@ https://bugzilla.mozilla.org/show_bug.cg
       gTest.window.document.body.focus();
 
       // WARNING: If the following test fails, give the setTimeout() in the onload()
       // a bit longer; the doc hasn't had enough time to setup its editor.
       is(gTest.window.document.body.innerHTML, gTest.expectedBodyBeforeEdit, "Is doc setup yet");
       sendString('EDITED ', gTest.window);
       is(gTest.window.document.body.innerHTML, gTest.expectedBodyAfterEdit, "Editing failed.");
 
-      gTest.window.location = 'data:text/html;charset=utf-8,SomeOtherDocument';
+      gTest.window.location = 'about:blank';
       SimpleTest.waitForFocus(goBack, gTest.window);
     }
-    
+
     function goBack() {
       window.onmessage = function(e) {
         window.onmessage = null;
         // Skip the test if the page is not loaded from the bf-cache when going back.
         if (e.data.persisted) {
           checkStillEditable();
         } else {
           gTest.window.close();
@@ -91,47 +86,46 @@ https://bugzilla.mozilla.org/show_bug.cg
       };
       gTest.window.history.back();
     }
 
     function checkStillEditable() {
 
       // Check that the contents are correct.
       is(gTest.window.document.body.innerHTML, gTest.expectedBodyAfterEdit, "Edited contents still correct?");
-      
+
       // Check that we can undo/redo and the contents are correct.
       gTest.window.document.execCommand("undo", false, null);
       is(gTest.window.document.body.innerHTML, gTest.expectedBodyBeforeEdit, "Can we undo?");
 
       gTest.window.document.execCommand("redo", false, null);
       is(gTest.window.document.body.innerHTML, gTest.expectedBodyAfterEdit, "Can we redo?");
-            
+
       // Check that we can still edit the page.
       gTest.window.document.body.focus();
       sendString('TWICE ', gTest.window);
       is(gTest.window.document.body.innerHTML, gTest.expectedBodyAfterSecondEdit, "Can we still edit?");
-      
+
       gTest.window.close();
       goNext();
-      
+
     }
-    
+
   </script>
-  
+
 </head>
 <body>
 <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=386782">Mozilla Bug 386782</a>
 <p id="display"></p>
 <div id="content" style="display: none">
-  
+
 </div>
 <pre id="test">
 <script class="testbody" type="text/javascript">
 
 /** Test for Bug 386782 **/
 
 SimpleTest.waitForExplicitFinish();
 
 </script>
 </pre>
 </body>
 </html>
-
--- a/dom/audiochannel/AudioChannelService.cpp
+++ b/dom/audiochannel/AudioChannelService.cpp
@@ -85,18 +85,18 @@ public:
     // TODO : remove b2g related event in bug1299390.
     observerService->NotifyObservers(wrapper,
                                      "media-playback",
                                      mActive
                                        ? u"active"
                                        : u"inactive");
 
     MOZ_LOG(AudioChannelService::GetAudioChannelLog(), LogLevel::Debug,
-           ("NotifyChannelActiveRunnable, type = %d, active = %d\n",
-            mAudioChannel, mActive));
+           ("NotifyChannelActiveRunnable, type = %" PRIu32 ", active = %d\n",
+            static_cast<uint32_t>(mAudioChannel), mActive));
 
     return NS_OK;
   }
 
 private:
   const uint64_t mWindowID;
   const AudioChannel mAudioChannel;
   const bool mActive;
@@ -842,18 +842,18 @@ AudioChannelService::SetAudioChannelVolu
                                            AudioChannel aAudioChannel,
                                            float aVolume)
 {
   MOZ_ASSERT(NS_IsMainThread());
   MOZ_ASSERT(aWindow);
   MOZ_ASSERT(aWindow->IsOuterWindow());
 
   MOZ_LOG(GetAudioChannelLog(), LogLevel::Debug,
-         ("AudioChannelService, SetAudioChannelVolume, window = %p, type = %d, "
-          "volume = %f\n", aWindow, aAudioChannel, aVolume));
+         ("AudioChannelService, SetAudioChannelVolume, window = %p, type = %" PRIu32 ", "
+          "volume = %f\n", aWindow, static_cast<uint32_t>(aAudioChannel), aVolume));
 
   AudioChannelWindow* winData = GetOrCreateWindowData(aWindow);
   winData->mChannels[(uint32_t)aAudioChannel].mVolume = aVolume;
   RefreshAgentsVolumeAndPropagate(aAudioChannel, aWindow);
 }
 
 NS_IMETHODIMP
 AudioChannelService::SetAudioChannelVolume(mozIDOMWindowProxy* aWindow,
@@ -903,18 +903,18 @@ AudioChannelService::SetAudioChannelMute
                                           AudioChannel aAudioChannel,
                                           bool aMuted)
 {
   MOZ_ASSERT(NS_IsMainThread());
   MOZ_ASSERT(aWindow);
   MOZ_ASSERT(aWindow->IsOuterWindow());
 
   MOZ_LOG(GetAudioChannelLog(), LogLevel::Debug,
-         ("AudioChannelService, SetAudioChannelMuted, window = %p, type = %d, "
-          "mute = %d\n", aWindow, aAudioChannel, aMuted));
+         ("AudioChannelService, SetAudioChannelMuted, window = %p, type = %" PRIu32 ", "
+          "mute = %d\n", aWindow, static_cast<uint32_t>(aAudioChannel), aMuted));
 
   if (aAudioChannel == AudioChannel::System) {
     // Workaround for bug1183033, system channel type can always playback.
     return;
   }
 
   AudioChannelWindow* winData = GetOrCreateWindowData(aWindow);
   winData->mChannels[(uint32_t)aAudioChannel].mMuted = aMuted;
--- a/dom/base/DOMException.cpp
+++ b/dom/base/DOMException.cpp
@@ -13,17 +13,16 @@
 #include "nsContentUtils.h"
 #include "nsCOMPtr.h"
 #include "nsIClassInfoImpl.h"
 #include "nsIDocument.h"
 #include "nsIDOMDOMException.h"
 #include "nsIException.h"
 #include "nsIProgrammingLanguage.h"
 #include "nsMemory.h"
-#include "prprf.h"
 #include "xpcprivate.h"
 
 #include "mozilla/dom/DOMExceptionBinding.h"
 #include "mozilla/ErrorResult.h"
 
 using namespace mozilla;
 
 enum DOM4ErrorTypeCodeMap {
@@ -356,17 +355,17 @@ Exception::GetData(nsISupports** aData)
 NS_IMETHODIMP
 Exception::ToString(JSContext* aCx, nsACString& _retval)
 {
   NS_ENSURE_TRUE(mInitialized, NS_ERROR_NOT_INITIALIZED);
 
   static const char defaultMsg[] = "<no message>";
   static const char defaultLocation[] = "<unknown>";
   static const char format[] =
-"[Exception... \"%s\"  nsresult: \"0x%x (%s)\"  location: \"%s\"  data: %s]";
+"[Exception... \"%s\"  nsresult: \"0x%" PRIx32 " (%s)\"  location: \"%s\"  data: %s]";
 
   nsCString location;
 
   if (mLocation) {
     // we need to free this if it does not fail
     nsresult rv = mLocation->ToString(aCx, location);
     NS_ENSURE_SUCCESS(rv, rv);
   }
@@ -384,17 +383,17 @@ Exception::ToString(JSContext* aCx, nsAC
     if (!msg) {
       msg = defaultMsg;
     }
     resultName = "<unknown>";
   }
   const char* data = mData ? "yes" : "no";
 
   _retval.Truncate();
-  _retval.AppendPrintf(format, msg, mResult, resultName,
+  _retval.AppendPrintf(format, msg, static_cast<uint32_t>(mResult), resultName,
                        location.get(), data);
   return NS_OK;
 }
 
 NS_IMETHODIMP
 Exception::Initialize(const nsACString& aMessage, nsresult aResult,
                       const nsACString& aName, nsIStackFrame *aLocation,
                       nsISupports *aData)
@@ -548,28 +547,28 @@ NS_IMETHODIMP
 DOMException::ToString(JSContext* aCx, nsACString& aReturn)
 {
   aReturn.Truncate();
 
   static const char defaultMsg[] = "<no message>";
   static const char defaultLocation[] = "<unknown>";
   static const char defaultName[] = "<unknown>";
   static const char format[] =
-    "[Exception... \"%s\"  code: \"%d\" nsresult: \"0x%x (%s)\"  location: \"%s\"]";
+    "[Exception... \"%s\"  code: \"%d\" nsresult: \"0x%" PRIx32 " (%s)\"  location: \"%s\"]";
 
   nsAutoCString location;
 
   if (location.IsEmpty()) {
     location = defaultLocation;
   }
 
   const char* msg = !mMessage.IsEmpty() ? mMessage.get() : defaultMsg;
   const char* resultName = !mName.IsEmpty() ? mName.get() : defaultName;
 
-  aReturn.AppendPrintf(format, msg, mCode, mResult, resultName,
+  aReturn.AppendPrintf(format, msg, mCode, static_cast<uint32_t>(mResult), resultName,
                        location.get());
 
   return NS_OK;
 }
 
 void
 DOMException::GetName(nsString& retval)
 {
--- a/dom/base/Element.cpp
+++ b/dom/base/Element.cpp
@@ -117,17 +117,16 @@
 #endif /* MOZ_XUL */
 
 #include "nsCycleCollectionParticipant.h"
 #include "nsCCUncollectableMarker.h"
 
 #include "mozAutoDocUpdate.h"
 
 #include "nsCSSParser.h"
-#include "prprf.h"
 #include "nsDOMMutationObserver.h"
 #include "nsWrapperCacheInlines.h"
 #include "xpcpublic.h"
 #include "nsIScriptError.h"
 #include "mozilla/Telemetry.h"
 
 #include "mozilla/CORSMode.h"
 #include "mozilla/dom/ShadowRoot.h"
--- a/dom/base/nsAttrValue.cpp
+++ b/dom/base/nsAttrValue.cpp
@@ -17,17 +17,16 @@
 #include "nsIAtom.h"
 #include "nsUnicharUtils.h"
 #include "mozilla/MemoryReporting.h"
 #include "mozilla/ServoBindingTypes.h"
 #include "mozilla/ServoStyleSet.h"
 #include "mozilla/DeclarationBlockInlines.h"
 #include "nsContentUtils.h"
 #include "nsReadableUtils.h"
-#include "prprf.h"
 #include "nsHTMLCSSStyleSheet.h"
 #include "nsCSSParser.h"
 #include "nsStyledElement.h"
 #include "nsIURI.h"
 #include "nsIDocument.h"
 #include <algorithm>
 
 #ifdef LoadImage
--- a/dom/base/nsDOMWindowUtils.cpp
+++ b/dom/base/nsDOMWindowUtils.cpp
@@ -1626,26 +1626,16 @@ nsDOMWindowUtils::GetIsMozAfterPaintPend
   nsPresContext* presContext = GetPresContext();
   if (!presContext)
     return NS_OK;
   *aResult = presContext->IsDOMPaintEventPending();
   return NS_OK;
 }
 
 NS_IMETHODIMP
-nsDOMWindowUtils::ClearMozAfterPaintEvents()
-{
-  nsPresContext* presContext = GetPresContext();
-  if (!presContext)
-    return NS_OK;
-  presContext->ClearMozAfterPaintEvents();
-  return NS_OK;
-}
-
-NS_IMETHODIMP
 nsDOMWindowUtils::DisableNonTestMouseEvents(bool aDisable)
 {
   nsCOMPtr<nsPIDOMWindowOuter> window = do_QueryReferent(mWindow);
   NS_ENSURE_TRUE(window, NS_ERROR_FAILURE);
   nsIDocShell *docShell = window->GetDocShell();
   NS_ENSURE_TRUE(docShell, NS_ERROR_FAILURE);
   nsCOMPtr<nsIPresShell> presShell = docShell->GetPresShell();
   NS_ENSURE_TRUE(presShell, NS_ERROR_FAILURE);
--- a/dom/base/nsGlobalWindow.cpp
+++ b/dom/base/nsGlobalWindow.cpp
@@ -187,17 +187,16 @@
 #include "nsIDragService.h"
 #include "mozilla/dom/Element.h"
 #include "mozilla/dom/Selection.h"
 #include "nsFrameLoader.h"
 #include "nsISupportsPrimitives.h"
 #include "nsXPCOMCID.h"
 #include "mozilla/Logging.h"
 #include "prenv.h"
-#include "prprf.h"
 
 #include "mozilla/dom/IDBFactory.h"
 #include "mozilla/dom/MessageChannel.h"
 #include "mozilla/dom/Promise.h"
 
 #include "mozilla/dom/Gamepad.h"
 #include "mozilla/dom/GamepadManager.h"
 
--- a/dom/base/nsIDocument.h
+++ b/dom/base/nsIDocument.h
@@ -3031,23 +3031,16 @@ protected:
   nsTArray<nsAutoPtr<nsPropertyTable> > mExtraPropertyTables;
 
   // Our cached .children collection
   nsCOMPtr<nsIHTMLCollection> mChildrenCollection;
 
   // container for per-context fonts (downloadable, SVG, etc.)
   RefPtr<mozilla::dom::FontFaceSet> mFontFaceSet;
 
-  // XXXheycam rust-bindgen currently doesn't generate correctly aligned fields
-  // to represent the following bitfields if they are preceded by something
-  // non-pointer aligned, so if adding non-pointer sized fields, please do so
-  // somewhere other than right here.
-  //
-  // https://github.com/servo/rust-bindgen/issues/111
-
   // True if BIDI is enabled.
   bool mBidiEnabled : 1;
   // True if a MathML element has ever been owned by this document.
   bool mMathMLEnabled : 1;
 
   // True if this document is the initial document for a window.  This should
   // basically be true only for documents that exist in newly-opened windows or
   // documents created to satisfy a GetDocument() on a window when there's no
--- a/dom/base/nsINode.cpp
+++ b/dom/base/nsINode.cpp
@@ -86,17 +86,16 @@
 #include "nsString.h"
 #include "nsStyleConsts.h"
 #include "nsSVGUtils.h"
 #include "nsTextNode.h"
 #include "nsUnicharUtils.h"
 #include "nsXBLBinding.h"
 #include "nsXBLPrototypeBinding.h"
 #include "mozilla/Preferences.h"
-#include "prprf.h"
 #include "xpcpublic.h"
 #include "nsCSSRuleProcessor.h"
 #include "nsCSSParser.h"
 #include "HTMLLegendElement.h"
 #include "nsWrapperCacheInlines.h"
 #include "WrapperFactory.h"
 #include "DocumentType.h"
 #include <algorithm>
--- a/dom/base/nsObjectLoadingContent.cpp
+++ b/dom/base/nsObjectLoadingContent.cpp
@@ -80,16 +80,17 @@
 #include "mozilla/dom/BindingUtils.h"
 #include "mozilla/dom/Element.h"
 #include "mozilla/dom/Event.h"
 #include "mozilla/dom/ScriptSettings.h"
 #include "mozilla/dom/PluginCrashedEvent.h"
 #include "mozilla/AsyncEventDispatcher.h"
 #include "mozilla/EventDispatcher.h"
 #include "mozilla/EventStates.h"
+#include "mozilla/IntegerPrintfMacros.h"
 #include "mozilla/Telemetry.h"
 #include "mozilla/dom/HTMLObjectElementBinding.h"
 #include "mozilla/dom/HTMLSharedObjectElement.h"
 #include "mozilla/dom/HTMLObjectElement.h"
 #include "nsChannelClassifier.h"
 
 #ifdef XP_WIN
 // Thanks so much, Microsoft! :(
@@ -807,17 +808,17 @@ nsObjectLoadingContent::InstantiatePlugi
     nsCOMPtr<nsIBlocklistService> blocklist =
       do_GetService("@mozilla.org/extensions/blocklist;1");
     if (blocklist) {
       uint32_t blockState = nsIBlocklistService::STATE_NOT_BLOCKED;
       blocklist->GetPluginBlocklistState(pluginTag, EmptyString(),
                                          EmptyString(), &blockState);
       if (blockState == nsIBlocklistService::STATE_OUTDATED) {
         // Fire plugin outdated event if necessary
-        LOG(("OBJLC [%p]: Dispatching plugin outdated event for content %p\n",
+        LOG(("OBJLC [%p]: Dispatching plugin outdated event for content\n",
              this));
         nsCOMPtr<nsIRunnable> ev = new nsSimplePluginEvent(thisContent,
                                                      NS_LITERAL_STRING("PluginOutdated"));
         nsresult rv = NS_DispatchToCurrentThread(ev);
         if (NS_FAILED(rv)) {
           NS_WARNING("failed to dispatch nsSimplePluginEvent");
         }
       }
@@ -2419,17 +2420,18 @@ nsObjectLoadingContent::LoadObject(bool 
                                   getter_AddRefs(finalListener));
       // finalListener will receive OnStartRequest below
     }
     break;
     case eType_Loading:
       // If our type remains Loading, we need a channel to proceed
       rv = OpenChannel();
       if (NS_FAILED(rv)) {
-        LOG(("OBJLC [%p]: OpenChannel returned failure (%u)", this, rv));
+        LOG(("OBJLC [%p]: OpenChannel returned failure (%" PRIu32 ")",
+             this, static_cast<uint32_t>(rv)));
       }
     break;
     case eType_Null:
       // Handled below, silence compiler warnings
     break;
   }
 
   //
@@ -2697,17 +2699,17 @@ nsObjectLoadingContent::UnloadObject(boo
 }
 
 void
 nsObjectLoadingContent::NotifyStateChanged(ObjectType aOldType,
                                            EventStates aOldState,
                                            bool aSync,
                                            bool aNotify)
 {
-  LOG(("OBJLC [%p]: Notifying about state change: (%u, %llx) -> (%u, %llx)"
+  LOG(("OBJLC [%p]: Notifying about state change: (%u, %" PRIx64 ") -> (%u, %" PRIx64 ")"
        " (sync %i, notify %i)", this, aOldType, aOldState.GetInternalValue(),
        mType, ObjectState().GetInternalValue(), aSync, aNotify));
 
   nsCOMPtr<nsIContent> thisContent =
     do_QueryInterface(static_cast<nsIImageLoadingContent*>(this));
   NS_ASSERTION(thisContent, "must be a content");
 
   NS_ASSERTION(thisContent->IsElement(), "Not an element?");
--- a/dom/base/nsWindowMemoryReporter.cpp
+++ b/dom/base/nsWindowMemoryReporter.cpp
@@ -163,17 +163,17 @@ GetWindowURI(nsGlobalWindow* aWindow)
 
 static void
 AppendWindowURI(nsGlobalWindow *aWindow, nsACString& aStr, bool aAnonymize)
 {
   nsCOMPtr<nsIURI> uri = GetWindowURI(aWindow);
 
   if (uri) {
     if (aAnonymize && !aWindow->IsChromeWindow()) {
-      aStr.AppendPrintf("<anonymized-%llu>", aWindow->WindowID());
+      aStr.AppendPrintf("<anonymized-%" PRIu64 ">", aWindow->WindowID());
     } else {
       nsCString spec = uri->GetSpecOrDefault();
 
       // A hack: replace forward slashes with '\\' so they aren't
       // treated as path separators.  Users of the reporters
       // (such as about:memory) have to undo this change.
       spec.ReplaceChar('/', '\\');
 
@@ -271,17 +271,17 @@ CollectWindowReports(nsGlobalWindow *aWi
     }
   }
 
   windowPath += NS_LITERAL_CSTRING("window-objects/");
 
   if (top) {
     windowPath += NS_LITERAL_CSTRING("top(");
     AppendWindowURI(top, windowPath, aAnonymize);
-    windowPath.AppendPrintf(", id=%llu)", top->WindowID());
+    windowPath.AppendPrintf(", id=%" PRIu64 ")", top->WindowID());
 
     aTopWindowPaths->Put(aWindow->WindowID(), windowPath);
 
     windowPath += aWindow->IsFrozen() ? NS_LITERAL_CSTRING("/cached/")
                                       : NS_LITERAL_CSTRING("/active/");
   } else {
     if (aGhostWindowIDs->Contains(aWindow->WindowID())) {
       windowPath += NS_LITERAL_CSTRING("top(none)/ghost/");
--- a/dom/browser-element/BrowserElementAudioChannel.cpp
+++ b/dom/browser-element/BrowserElementAudioChannel.cpp
@@ -50,18 +50,18 @@ BrowserElementAudioChannel::Create(nsPID
     new BrowserElementAudioChannel(aWindow, aFrameLoader, aAPI, aAudioChannel);
 
   aRv = ac->Initialize();
   if (NS_WARN_IF(aRv.Failed())) {
     return nullptr;
   }
 
   MOZ_LOG(AudioChannelService::GetAudioChannelLog(), LogLevel::Debug,
-         ("BrowserElementAudioChannel, Create, channel = %p, type = %d\n",
-          ac.get(), aAudioChannel));
+         ("BrowserElementAudioChannel, Create, channel = %p, type = %" PRIu32 "\n",
+          ac.get(), static_cast<uint32_t>(aAudioChannel)));
 
   return ac.forget();
 }
 
 BrowserElementAudioChannel::BrowserElementAudioChannel(
 						nsPIDOMWindowInner* aWindow,
 						nsIFrameLoader* aFrameLoader,
                                                 nsIBrowserElementAPI* aAPI,
@@ -509,17 +509,17 @@ BrowserElementAudioChannel::Observe(nsIS
   return NS_OK;
 }
 
 void
 BrowserElementAudioChannel::ProcessStateChanged(const char16_t* aData)
 {
   MOZ_LOG(AudioChannelService::GetAudioChannelLog(), LogLevel::Debug,
          ("BrowserElementAudioChannel, ProcessStateChanged, this = %p, "
-          "type = %d\n", this, mAudioChannel));
+          "type = %" PRIu32 "\n", this, static_cast<uint32_t>(mAudioChannel)));
 
   nsAutoString value(aData);
   mState = value.EqualsASCII("active") ? eStateActive : eStateInactive;
   DispatchTrustedEvent(NS_LITERAL_STRING("activestatechanged"));
 }
 
 bool
 BrowserElementAudioChannel::IsSystemAppWindow(nsPIDOMWindowOuter* aWindow) const
--- a/dom/canvas/CanvasUtils.cpp
+++ b/dom/canvas/CanvasUtils.cpp
@@ -1,18 +1,16 @@
 /* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include <stdlib.h>
 #include <stdarg.h>
 
-#include "prprf.h"
-
 #include "nsIServiceManager.h"
 
 #include "nsIConsoleService.h"
 #include "nsIDOMCanvasRenderingContext2D.h"
 #include "nsICanvasRenderingContextInternal.h"
 #include "nsIHTMLCollection.h"
 #include "mozilla/dom/HTMLCanvasElement.h"
 #include "nsIPrincipal.h"
--- a/dom/canvas/TexUnpackBlob.cpp
+++ b/dom/canvas/TexUnpackBlob.cpp
@@ -239,17 +239,17 @@ ValidateUnpackBytes(WebGLContext* webgl,
         return true;
 
     const auto bytesPerPixel = webgl::BytesPerPixel(pi);
     const auto bytesPerRow = CheckedUint32(blob->mRowLength) * bytesPerPixel;
     const auto rowStride = RoundUpToMultipleOf(bytesPerRow, blob->mAlignment);
 
     const auto fullRows = availByteCount / rowStride;
     if (!fullRows.isValid()) {
-        webgl->ErrorOutOfMemory("%s: Unacceptable upload size calculated.");
+        webgl->ErrorOutOfMemory("%s: Unacceptable upload size calculated.", funcName);
         return false;
     }
 
     const auto bodyBytes = fullRows.value() * rowStride.value();
     const auto tailPixels = (availByteCount - bodyBytes) / bytesPerPixel;
 
     return ValidateUnpackPixels(webgl, funcName, fullRows.value(), tailPixels, blob);
 }
--- a/dom/canvas/WebGL2ContextMRTs.cpp
+++ b/dom/canvas/WebGL2ContextMRTs.cpp
@@ -2,16 +2,17 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "WebGL2Context.h"
 
 #include "GLContext.h"
 #include "WebGLFramebuffer.h"
+#include "mozilla/SizePrintfMacros.h"
 
 namespace mozilla {
 
 bool
 WebGL2Context::ValidateClearBuffer(const char* funcName, GLenum buffer, GLint drawBuffer,
                                    size_t availElemCount, GLuint elemOffset,
                                    GLenum funcType)
 {
@@ -50,17 +51,17 @@ WebGL2Context::ValidateClearBuffer(const
     if (drawBuffer < 0 || drawBuffer > maxDrawBuffer) {
         ErrorInvalidValue("%s: Invalid drawbuffer %d. This buffer only supports"
                           " `drawbuffer` values between 0 and %u.",
                           funcName, drawBuffer, maxDrawBuffer);
         return false;
     }
 
     if (availElemCount < requiredElements) {
-        ErrorInvalidValue("%s: Not enough elements. Require %u. Given %u.",
+        ErrorInvalidValue("%s: Not enough elements. Require %" PRIuSIZE ". Given %" PRIuSIZE ".",
                           funcName, requiredElements, availElemCount);
         return false;
     }
 
     ////
 
     MakeContextCurrent();
 
--- a/dom/canvas/WebGLContext.cpp
+++ b/dom/canvas/WebGLContext.cpp
@@ -27,16 +27,17 @@
 #include "mozilla/dom/HTMLVideoElement.h"
 #include "mozilla/dom/ImageData.h"
 #include "mozilla/dom/WebGLContextEvent.h"
 #include "mozilla/EnumeratedArrayCycleCollection.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/ProcessPriorityManager.h"
 #include "mozilla/ScopeExit.h"
 #include "mozilla/Services.h"
+#include "mozilla/SizePrintfMacros.h"
 #include "mozilla/Telemetry.h"
 #include "nsContentUtils.h"
 #include "nsDisplayList.h"
 #include "nsError.h"
 #include "nsIClassInfoImpl.h"
 #include "nsIConsoleService.h"
 #include "nsIDOMEvent.h"
 #include "nsIGfxInfo.h"
@@ -749,17 +750,17 @@ WebGLContext::CreateAndInitGL(bool force
         FailureReason reason;
         if (IsFeatureInBlacklist(gfxInfo, feature, &reason.key)) {
             reason.info = "Refused to create native OpenGL context because of blacklist"
                           " entry: ";
             reason.info.Append(reason.key);
 
             out_failReasons->push_back(reason);
 
-            GenerateWarning(reason.info.BeginReading());
+            GenerateWarning("%s", reason.info.BeginReading());
             tryNativeGL = false;
         }
     }
 
     //////
 
     if (tryNativeGL) {
         if (useEGL)
@@ -1206,23 +1207,23 @@ WebGLContext::LoseOldestWebGLContextIfLi
             if (contexts[i]->mLastUseIndex < oldestIndexThisPrincipal) {
                 oldestIndexThisPrincipal = contexts[i]->mLastUseIndex;
                 oldestContextThisPrincipal = contexts[i];
             }
         }
     }
 
     if (numContextsThisPrincipal > kMaxWebGLContextsPerPrincipal) {
-        GenerateWarning("Exceeded %d live WebGL contexts for this principal, losing the "
+        GenerateWarning("Exceeded %" PRIuSIZE " live WebGL contexts for this principal, losing the "
                         "least recently used one.", kMaxWebGLContextsPerPrincipal);
         MOZ_ASSERT(oldestContextThisPrincipal); // if we reach this point, this can't be null
         const_cast<WebGLContext*>(oldestContextThisPrincipal)->LoseContext();
     } else if (numContexts > kMaxWebGLContexts) {
-        GenerateWarning("Exceeded %d live WebGL contexts, losing the least recently used one.",
-                        kMaxWebGLContexts);
+        GenerateWarning("Exceeded %" PRIuSIZE " live WebGL contexts, losing the least "
+                        "recently used one.", kMaxWebGLContexts);
         MOZ_ASSERT(oldestContext); // if we reach this point, this can't be null
         const_cast<WebGLContext*>(oldestContext)->LoseContext();
     }
 }
 
 UniquePtr<uint8_t[]>
 WebGLContext::GetImageBuffer(int32_t* out_format)
 {
--- a/dom/canvas/WebGLContext.h
+++ b/dom/canvas/WebGLContext.h
@@ -395,27 +395,27 @@ public:
      */
     virtual void DidRefresh() override;
 
     NS_IMETHOD Redraw(const gfxRect&) override {
         return NS_ERROR_NOT_IMPLEMENTED;
     }
 
     void SynthesizeGLError(GLenum err);
-    void SynthesizeGLError(GLenum err, const char* fmt, ...);
+    void SynthesizeGLError(GLenum err, const char* fmt, ...) MOZ_FORMAT_PRINTF(3, 4);
 
-    void ErrorInvalidEnum(const char* fmt = 0, ...);
-    void ErrorInvalidOperation(const char* fmt = 0, ...);
-    void ErrorInvalidValue(const char* fmt = 0, ...);
-    void ErrorInvalidFramebufferOperation(const char* fmt = 0, ...);
+    void ErrorInvalidEnum(const char* fmt = 0, ...) MOZ_FORMAT_PRINTF(2, 3);
+    void ErrorInvalidOperation(const char* fmt = 0, ...) MOZ_FORMAT_PRINTF(2, 3);
+    void ErrorInvalidValue(const char* fmt = 0, ...) MOZ_FORMAT_PRINTF(2, 3);
+    void ErrorInvalidFramebufferOperation(const char* fmt = 0, ...) MOZ_FORMAT_PRINTF(2, 3);
     void ErrorInvalidEnumInfo(const char* info, GLenum enumValue);
     void ErrorInvalidEnumInfo(const char* info, const char* funcName,
                               GLenum enumValue);
-    void ErrorOutOfMemory(const char* fmt = 0, ...);
-    void ErrorImplementationBug(const char* fmt = 0, ...);
+    void ErrorOutOfMemory(const char* fmt = 0, ...) MOZ_FORMAT_PRINTF(2, 3);
+    void ErrorImplementationBug(const char* fmt = 0, ...) MOZ_FORMAT_PRINTF(2, 3);
 
     void ErrorInvalidEnumArg(const char* funcName, const char* argName, GLenum val);
 
     const char* ErrorName(GLenum error);
 
     /**
      * Return displayable name for GLenum.
      * This version is like gl::GLenumToStr but with out the GL_ prefix to
@@ -2042,20 +2042,20 @@ protected:
     // these objects at high frequency. Having WebGLContext's hold one such object seems fine,
     // because WebGLContext objects only go away during GC, which shouldn't happen too frequently.
     // If in the future GC becomes much more frequent, we may have to revisit then (maybe use a timer).
     ForceDiscreteGPUHelperCGL mForceDiscreteGPUHelper;
 #endif
 
 public:
     // console logging helpers
-    void GenerateWarning(const char* fmt, ...);
+    void GenerateWarning(const char* fmt, ...) MOZ_FORMAT_PRINTF(2, 3);
     void GenerateWarning(const char* fmt, va_list ap);
 
-    void GeneratePerfWarning(const char* fmt, ...) const;
+    void GeneratePerfWarning(const char* fmt, ...) const MOZ_FORMAT_PRINTF(2, 3);
 
 public:
     UniquePtr<webgl::FormatUsageAuthority> mFormatUsage;
 
     virtual UniquePtr<webgl::FormatUsageAuthority>
     CreateFormatUsage(gl::GLContext* gl) const = 0;
 
 
--- a/dom/canvas/WebGLContextState.cpp
+++ b/dom/canvas/WebGLContextState.cpp
@@ -642,17 +642,17 @@ WebGLContext::GetParameterIndexed(JSCont
     }
 
     MakeContextCurrent();
 
     switch (pname) {
         case LOCAL_GL_TRANSFORM_FEEDBACK_BUFFER_BINDING:
         {
             if (index >= mGLMaxTransformFeedbackSeparateAttribs) {
-                ErrorInvalidValue("getParameterIndexed: index should be less than MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS", index);
+                ErrorInvalidValue("getParameterIndexed: index should be less than MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS");
                 retval.setNull();
                 return;
             }
             retval.setNull(); // See bug 903594
             return;
         }
 
         default:
--- a/dom/canvas/WebGLContextUtils.cpp
+++ b/dom/canvas/WebGLContextUtils.cpp
@@ -5,23 +5,23 @@
 
 #include "WebGLContextUtils.h"
 #include "WebGLContext.h"
 
 #include "GLContext.h"
 #include "jsapi.h"
 #include "mozilla/dom/ScriptSettings.h"
 #include "mozilla/Preferences.h"
+#include "mozilla/Sprintf.h"
 #include "nsIDOMDataContainerEvent.h"
 #include "nsIDOMEvent.h"
 #include "nsIScriptSecurityManager.h"
 #include "nsIVariant.h"
 #include "nsPrintfCString.h"
 #include "nsServiceManagerUtils.h"
-#include "prprf.h"
 #include <stdarg.h>
 #include "WebGLBuffer.h"
 #include "WebGLExtensions.h"
 #include "WebGLFramebuffer.h"
 #include "WebGLProgram.h"
 #include "WebGLTexture.h"
 #include "WebGLVertexArray.h"
 
@@ -71,17 +71,17 @@ void
 WebGLContext::GenerateWarning(const char* fmt, va_list ap)
 {
     if (!ShouldGenerateWarnings())
         return;
 
     mAlreadyGeneratedWarnings++;
 
     char buf[1024];
-    PR_vsnprintf(buf, 1024, fmt, ap);
+    VsprintfLiteral(buf, fmt, ap);
 
     // no need to print to stderr, as JS_ReportWarning takes care of this for us.
 
     if (!mCanvasElement) {
         return;
     }
 
     dom::AutoJSAPI api;
@@ -124,17 +124,17 @@ WebGLContext::GeneratePerfWarning(const 
     JSContext* cx = api.cx();
 
     ////
 
     va_list ap;
     va_start(ap, fmt);
 
     char buf[1024];
-    PR_vsnprintf(buf, 1024, fmt, ap);
+    VsprintfLiteral(buf, fmt, ap);
 
     va_end(ap);
 
     ////
 
     JS_ReportWarningASCII(cx, "WebGL perf warning: %s", buf);
     mNumPerfWarnings++;
 
--- a/dom/canvas/WebGLProgram.cpp
+++ b/dom/canvas/WebGLProgram.cpp
@@ -5,16 +5,17 @@
 
 #include "WebGLProgram.h"
 
 #include "GLContext.h"
 #include "mozilla/CheckedInt.h"
 #include "mozilla/dom/WebGL2RenderingContextBinding.h"
 #include "mozilla/dom/WebGLRenderingContextBinding.h"
 #include "mozilla/RefPtr.h"
+#include "mozilla/SizePrintfMacros.h"
 #include "nsPrintfCString.h"
 #include "WebGLActiveInfo.h"
 #include "WebGLContext.h"
 #include "WebGLShader.h"
 #include "WebGLTransformFeedback.h"
 #include "WebGLUniformLocation.h"
 #include "WebGLValidateStrings.h"
 
@@ -594,17 +595,17 @@ WebGLProgram::GetActiveAttrib(GLuint ind
     if (!mMostRecentLinkInfo) {
         RefPtr<WebGLActiveInfo> ret = WebGLActiveInfo::CreateInvalid(mContext);
         return ret.forget();
     }
 
     const auto& attribs = mMostRecentLinkInfo->attribs;
 
     if (index >= attribs.size()) {
-        mContext->ErrorInvalidValue("`index` (%i) must be less than %s (%i).",
+        mContext->ErrorInvalidValue("`index` (%i) must be less than %s (%" PRIuSIZE ").",
                                     index, "ACTIVE_ATTRIBS", attribs.size());
         return nullptr;
     }
 
     RefPtr<WebGLActiveInfo> ret = attribs[index].mActiveInfo;
     return ret.forget();
 }
 
@@ -615,17 +616,17 @@ WebGLProgram::GetActiveUniform(GLuint in
         // According to the spec, this can return null.
         RefPtr<WebGLActiveInfo> ret = WebGLActiveInfo::CreateInvalid(mContext);
         return ret.forget();
     }
 
     const auto& uniforms = mMostRecentLinkInfo->uniforms;
 
     if (index >= uniforms.size()) {
-        mContext->ErrorInvalidValue("`index` (%i) must be less than %s (%i).",
+        mContext->ErrorInvalidValue("`index` (%i) must be less than %s (%" PRIuSIZE ").",
                                     index, "ACTIVE_UNIFORMS", uniforms.size());
         return nullptr;
     }
 
     RefPtr<WebGLActiveInfo> ret = uniforms[index]->mActiveInfo;
     return ret.forget();
 }
 
--- a/dom/canvas/WebGLQuery.cpp
+++ b/dom/canvas/WebGLQuery.cpp
@@ -230,18 +230,17 @@ WebGLQuery::DeleteQuery()
 
     RequestDelete();
 }
 
 void
 WebGLQuery::QueryCounter(const char* funcName, GLenum target)
 {
     if (target != LOCAL_GL_TIMESTAMP_EXT) {
-        mContext->ErrorInvalidEnum("%s: `target` must be TIMESTAMP_EXT.", funcName,
-                                   target);
+        mContext->ErrorInvalidEnum("%s: `target` must be TIMESTAMP_EXT.", funcName);
         return;
     }
 
     if (mTarget && target != mTarget) {
         mContext->ErrorInvalidOperation("%s: Queries cannot change targets.", funcName);
         return;
     }
 
--- a/dom/canvas/WebGLShader.cpp
+++ b/dom/canvas/WebGLShader.cpp
@@ -4,16 +4,17 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "WebGLShader.h"
 
 #include "angle/ShaderLang.h"
 #include "GLContext.h"
 #include "mozilla/dom/WebGLRenderingContextBinding.h"
 #include "mozilla/MemoryReporting.h"
+#include "mozilla/SizePrintfMacros.h"
 #include "nsPrintfCString.h"
 #include "nsString.h"
 #include "prenv.h"
 #include "WebGLContext.h"
 #include "WebGLObjectModel.h"
 #include "WebGLShaderValidator.h"
 #include "WebGLValidateStrings.h"
 
--- a/dom/canvas/WebGLTextureUpload.cpp
+++ b/dom/canvas/WebGLTextureUpload.cpp
@@ -12,16 +12,17 @@
 #include "GLBlitHelper.h"
 #include "GLContext.h"
 #include "mozilla/gfx/2D.h"
 #include "mozilla/dom/HTMLVideoElement.h"
 #include "mozilla/dom/ImageBitmap.h"
 #include "mozilla/dom/ImageData.h"
 #include "mozilla/MathAlgorithms.h"
 #include "mozilla/Scoped.h"
+#include "mozilla/SizePrintfMacros.h"
 #include "mozilla/Unused.h"
 #include "ScopedGLHelpers.h"
 #include "TexUnpackBlob.h"
 #include "WebGLBuffer.h"
 #include "WebGLContext.h"
 #include "WebGLContextUtils.h"
 #include "WebGLFramebuffer.h"
 #include "WebGLTexelConversions.h"
@@ -690,17 +691,17 @@ ValidateCompressedTexUnpack(WebGLContext
     if (!bytesNeeded.isValid()) {
         webgl->ErrorOutOfMemory("%s: Overflow while computing the needed buffer size.",
                                 funcName);
         return false;
     }
 
     if (dataSize != bytesNeeded.value()) {
         webgl->ErrorInvalidValue("%s: Provided buffer's size must match expected size."
-                                 " (needs %u, has %u)",
+                                 " (needs %u, has %" PRIuSIZE ")",
                                  funcName, bytesNeeded.value(), dataSize);
         return false;
     }
 
     return true;
 }
 
 static bool
@@ -1389,17 +1390,17 @@ WebGLTexture::TexSubImage(const char* fu
 
     if (glError == LOCAL_GL_OUT_OF_MEMORY) {
         mContext->ErrorOutOfMemory("%s: Driver ran out of memory during upload.",
                                    funcName);
         return;
     }
 
     if (glError) {
-        mContext->ErrorInvalidOperation("%s: Unexpected error during upload: 0x04x",
+        mContext->ErrorInvalidOperation("%s: Unexpected error during upload: 0x%04x",
                                         funcName, glError);
         MOZ_ASSERT(false, "Unexpected GL error.");
         return;
     }
 
     ////////////////////////////////////
     // Update our specification data?
 
--- a/dom/canvas/WebGLUniformLocation.cpp
+++ b/dom/canvas/WebGLUniformLocation.cpp
@@ -1,16 +1,17 @@
 /* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "WebGLUniformLocation.h"
 
 #include "GLContext.h"
+#include "mozilla/SizePrintfMacros.h"
 #include "mozilla/dom/ToJSValue.h"
 #include "mozilla/dom/WebGLRenderingContextBinding.h"
 #include "WebGLActiveInfo.h"
 #include "WebGLContext.h"
 #include "WebGLProgram.h"
 
 namespace mozilla {
 
@@ -147,34 +148,34 @@ WebGLUniformLocation::ValidateArrayLengt
                                           const char* funcName) const
 {
     MOZ_ASSERT(mLinkInfo);
 
     if (setterArraySize == 0 ||
         setterArraySize % setterElemSize)
     {
         mContext->ErrorInvalidValue("%s: Expected an array of length a multiple of %d,"
-                                    " got an array of length %d.",
+                                    " got an array of length %" PRIuSIZE ".",
                                     funcName, setterElemSize, setterArraySize);
         return false;
     }
 
     /* GLES 2.0.25, Section 2.10, p38
      *   When loading `N` elements starting at an arbitrary position `k` in a uniform
      *   declared as an array, elements `k` through `k + N - 1` in the array will be
      *   replaced with the new values. Values for any array element that exceeds the
      *   highest array element index used, as reported by `GetActiveUniform`, will be
      *   ignored by GL.
      */
     if (!mInfo->mActiveInfo->mIsArray &&
         setterArraySize != setterElemSize)
     {
         mContext->ErrorInvalidOperation("%s: Expected an array of length exactly %d"
                                         " (since this uniform is not an array uniform),"
-                                        " got an array of length %d.",
+                                        " got an array of length %" PRIuSIZE ".",
                                         funcName, setterElemSize, setterArraySize);
         return false;
     }
 
     return true;
 }
 
 JS::Value
--- a/dom/events/IMEStateManager.cpp
+++ b/dom/events/IMEStateManager.cpp
@@ -9,16 +9,17 @@
 #include "mozilla/IMEStateManager.h"
 
 #include "mozilla/Attributes.h"
 #include "mozilla/EventListenerManager.h"
 #include "mozilla/EventStates.h"
 #include "mozilla/MouseEvents.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/Services.h"
+#include "mozilla/SizePrintfMacros.h"
 #include "mozilla/TextComposition.h"
 #include "mozilla/TextEvents.h"
 #include "mozilla/Unused.h"
 #include "mozilla/dom/HTMLFormElement.h"
 #include "mozilla/dom/TabParent.h"
 
 #include "HTMLInputElement.h"
 #include "IMEContentObserver.h"
@@ -157,17 +158,17 @@ IMEStateManager::Init()
     false);
 }
 
 // static
 void
 IMEStateManager::Shutdown()
 {
   MOZ_LOG(sISMLog, LogLevel::Info,
-    ("Shutdown(), sTextCompositions=0x%p, sTextCompositions->Length()=%u",
+    ("Shutdown(), sTextCompositions=0x%p, sTextCompositions->Length()=%" PRIuSIZE,
      sTextCompositions, sTextCompositions ? sTextCompositions->Length() : 0));
 
   MOZ_ASSERT(!sTextCompositions || !sTextCompositions->Length());
   delete sTextCompositions;
   sTextCompositions = nullptr;
 }
 
 // static
@@ -259,17 +260,17 @@ IMEStateManager::OnDestroyPresContext(ns
 
   // First, if there is a composition in the aPresContext, clean up it.
   if (sTextCompositions) {
     TextCompositionArray::index_type i =
       sTextCompositions->IndexOf(aPresContext);
     if (i != TextCompositionArray::NoIndex) {
       MOZ_LOG(sISMLog, LogLevel::Debug,
         ("  OnDestroyPresContext(), "
-         "removing TextComposition instance from the array (index=%u)", i));
+         "removing TextComposition instance from the array (index=%" PRIuSIZE ")", i));
       // there should be only one composition per presContext object.
       sTextCompositions->ElementAt(i)->Destroy();
       sTextCompositions->RemoveElementAt(i);
       if (sTextCompositions->IndexOf(aPresContext) !=
             TextCompositionArray::NoIndex) {
         MOZ_LOG(sISMLog, LogLevel::Error,
           ("  OnDestroyPresContext(), FAILED to remove "
            "TextComposition instance from the array"));
@@ -909,17 +910,17 @@ IMEStateManager::SetInputContextForChild
                    TabParent* aTabParent,
                    const InputContext& aInputContext,
                    const InputContextAction& aAction)
 {
   MOZ_LOG(sISMLog, LogLevel::Info,
     ("SetInputContextForChildProcess(aTabParent=0x%p, "
      "aInputContext={ mIMEState={ mEnabled=%s, mOpen=%s }, "
      "mHTMLInputType=\"%s\", mHTMLInputInputmode=\"%s\", mActionHint=\"%s\" }, "
-     "aAction={ mCause=%s, mAction=%s }, aTabParent=0x%p), sPresContext=0x%p, "
+     "aAction={ mCause=%s, mAction=%s }), sPresContext=0x%p, "
      "sActiveTabParent=0x%p",
      aTabParent, GetIMEStateEnabledName(aInputContext.mIMEState.mEnabled),
      GetIMEStateSetOpenName(aInputContext.mIMEState.mOpen),
      NS_ConvertUTF16toUTF8(aInputContext.mHTMLInputType).get(),
      NS_ConvertUTF16toUTF8(aInputContext.mHTMLInputInputmode).get(),
      NS_ConvertUTF16toUTF8(aInputContext.mActionHint).get(),
      GetActionCauseName(aAction.mCause),
      GetActionFocusChangeName(aAction.mFocusChange),
@@ -1100,20 +1101,20 @@ IMEStateManager::DispatchCompositionEven
 {
   RefPtr<TabParent> tabParent =
     aEventTargetNode->IsContent() ?
       TabParent::GetFrom(aEventTargetNode->AsContent()) : nullptr;
 
   MOZ_LOG(sISMLog, LogLevel::Info,
     ("DispatchCompositionEvent(aNode=0x%p, "
      "aPresContext=0x%p, aCompositionEvent={ mMessage=%s, "
-     "mNativeIMEContext={ mRawNativeIMEContext=0x%X, "
-     "mOriginProcessID=0x%X }, mWidget(0x%p)={ "
-     "GetNativeIMEContext()={ mRawNativeIMEContext=0x%X, "
-     "mOriginProcessID=0x%X }, Destroyed()=%s }, "
+     "mNativeIMEContext={ mRawNativeIMEContext=0x%" PRIXPTR ", "
+     "mOriginProcessID=0x%" PRIX64 " }, mWidget(0x%p)={ "
+     "GetNativeIMEContext()={ mRawNativeIMEContext=0x%" PRIXPTR ", "
+     "mOriginProcessID=0x%" PRIX64 " }, Destroyed()=%s }, "
      "mFlags={ mIsTrusted=%s, mPropagationStopped=%s } }, "
      "aIsSynthesized=%s), tabParent=%p",
      aEventTargetNode, aPresContext,
      ToChar(aCompositionEvent->mMessage),
      aCompositionEvent->mNativeIMEContext.mRawNativeIMEContext,
      aCompositionEvent->mNativeIMEContext.mOriginProcessID,
      aCompositionEvent->mWidget.get(),
      aCompositionEvent->mWidget->GetNativeIMEContext().mRawNativeIMEContext,
@@ -1250,20 +1251,20 @@ void
 IMEStateManager::OnCompositionEventDiscarded(
                    WidgetCompositionEvent* aCompositionEvent)
 {
   // Note that this method is never called for synthesized events for emulating
   // commit or cancel composition.
 
   MOZ_LOG(sISMLog, LogLevel::Info,
     ("OnCompositionEventDiscarded(aCompositionEvent={ "
-     "mMessage=%s, mNativeIMEContext={ mRawNativeIMEContext=0x%X, "
-     "mOriginProcessID=0x%X }, mWidget(0x%p)={ "
-     "GetNativeIMEContext()={ mRawNativeIMEContext=0x%X, "
-     "mOriginProcessID=0x%X }, Destroyed()=%s }, "
+     "mMessage=%s, mNativeIMEContext={ mRawNativeIMEContext=0x%" PRIXPTR ", "
+     "mOriginProcessID=0x%" PRIX64 " }, mWidget(0x%p)={ "
+     "GetNativeIMEContext()={ mRawNativeIMEContext=0x%" PRIXPTR ", "
+     "mOriginProcessID=0x%" PRIX64 " }, Destroyed()=%s }, "
      "mFlags={ mIsTrusted=%s } })",
      ToChar(aCompositionEvent->mMessage),
      aCompositionEvent->mNativeIMEContext.mRawNativeIMEContext,
      aCompositionEvent->mNativeIMEContext.mOriginProcessID,
      aCompositionEvent->mWidget.get(),
      aCompositionEvent->mWidget->GetNativeIMEContext().mRawNativeIMEContext,
      aCompositionEvent->mWidget->GetNativeIMEContext().mOriginProcessID,
      GetBoolName(aCompositionEvent->mWidget->Destroyed()),
--- a/dom/events/NotifyPaintEvent.cpp
+++ b/dom/events/NotifyPaintEvent.cpp
@@ -14,26 +14,26 @@
 
 namespace mozilla {
 namespace dom {
 
 NotifyPaintEvent::NotifyPaintEvent(EventTarget* aOwner,
                                    nsPresContext* aPresContext,
                                    WidgetEvent* aEvent,
                                    EventMessage aEventMessage,
-                                   nsInvalidateRequestList* aInvalidateRequests,
+                                   nsTArray<nsRect>* aInvalidateRequests,
                                    uint64_t aTransactionId,
                                    DOMHighResTimeStamp aTimeStamp)
   : Event(aOwner, aPresContext, aEvent)
 {
   if (mEvent) {
     mEvent->mMessage = aEventMessage;
   }
   if (aInvalidateRequests) {
-    mInvalidateRequests.AppendElements(Move(aInvalidateRequests->mRequests));
+    mInvalidateRequests.SwapElements(*aInvalidateRequests);
   }
 
   mTransactionId = aTransactionId;
   mTimeStamp = aTimeStamp;
 }
 
 NS_INTERFACE_MAP_BEGIN(NotifyPaintEvent)
   NS_INTERFACE_MAP_ENTRY(nsIDOMNotifyPaintEvent)
@@ -42,17 +42,17 @@ NS_INTERFACE_MAP_END_INHERITING(Event)
 NS_IMPL_ADDREF_INHERITED(NotifyPaintEvent, Event)
 NS_IMPL_RELEASE_INHERITED(NotifyPaintEvent, Event)
 
 nsRegion
 NotifyPaintEvent::GetRegion(SystemCallerGuarantee)
 {
   nsRegion r;
   for (uint32_t i = 0; i < mInvalidateRequests.Length(); ++i) {
-    r.Or(r, mInvalidateRequests[i].mRect);
+    r.Or(r, mInvalidateRequests[i]);
     r.SimplifyOutward(10);
   }
   return r;
 }
 
 already_AddRefed<DOMRect>
 NotifyPaintEvent::BoundingClientRect(SystemCallerGuarantee aGuarantee)
 {
@@ -104,33 +104,31 @@ NotifyPaintEvent::Serialize(IPC::Message
     IPC::WriteParam(aMsg, NS_LITERAL_STRING("notifypaintevent"));
   }
 
   Event::Serialize(aMsg, false);
 
   uint32_t length = mInvalidateRequests.Length();
   IPC::WriteParam(aMsg, length);
   for (uint32_t i = 0; i < length; ++i) {
-    IPC::WriteParam(aMsg, mInvalidateRequests[i].mRect);
-    IPC::WriteParam(aMsg, mInvalidateRequests[i].mFlags);
+    IPC::WriteParam(aMsg, mInvalidateRequests[i]);
   }
 }
 
 NS_IMETHODIMP_(bool)
 NotifyPaintEvent::Deserialize(const IPC::Message* aMsg, PickleIterator* aIter)
 {
   NS_ENSURE_TRUE(Event::Deserialize(aMsg, aIter), false);
 
   uint32_t length = 0;
   NS_ENSURE_TRUE(IPC::ReadParam(aMsg, aIter, &length), false);
   mInvalidateRequests.SetCapacity(length);
   for (uint32_t i = 0; i < length; ++i) {
-    nsInvalidateRequestList::Request req;
-    NS_ENSURE_TRUE(IPC::ReadParam(aMsg, aIter, &req.mRect), false);
-    NS_ENSURE_TRUE(IPC::ReadParam(aMsg, aIter, &req.mFlags), false);
+    nsRect req;
+    NS_ENSURE_TRUE(IPC::ReadParam(aMsg, aIter, &req), false);
     mInvalidateRequests.AppendElement(req);
   }
 
   return true;
 }
 
 uint64_t
 NotifyPaintEvent::TransactionId(SystemCallerGuarantee)
@@ -150,17 +148,17 @@ NotifyPaintEvent::PaintTimeStamp(SystemC
 using namespace mozilla;
 using namespace mozilla::dom;
 
 already_AddRefed<NotifyPaintEvent>
 NS_NewDOMNotifyPaintEvent(EventTarget* aOwner,
                           nsPresContext* aPresContext,
                           WidgetEvent* aEvent,
                           EventMessage aEventMessage,
-                          nsInvalidateRequestList* aInvalidateRequests,
+                          nsTArray<nsRect>* aInvalidateRequests,
                           uint64_t aTransactionId,
                           DOMHighResTimeStamp aTimeStamp)
 {
   RefPtr<NotifyPaintEvent> it =
     new NotifyPaintEvent(aOwner, aPresContext, aEvent, aEventMessage,
                          aInvalidateRequests, aTransactionId, aTimeStamp);
   return it.forget();
 }
--- a/dom/events/NotifyPaintEvent.h
+++ b/dom/events/NotifyPaintEvent.h
@@ -25,17 +25,17 @@ class NotifyPaintEvent : public Event,
                          public nsIDOMNotifyPaintEvent
 {
 
 public:
   NotifyPaintEvent(EventTarget* aOwner,
                    nsPresContext* aPresContext,
                    WidgetEvent* aEvent,
                    EventMessage aEventMessage,
-                   nsInvalidateRequestList* aInvalidateRequests,
+                   nsTArray<nsRect>* aInvalidateRequests,
                    uint64_t aTransactionId,
                    DOMHighResTimeStamp aTimeStamp);
 
   NS_DECL_ISUPPORTS_INHERITED
 
   NS_DECL_NSIDOMNOTIFYPAINTEVENT
 
   // Forward to base class
@@ -63,29 +63,28 @@ public:
   DOMHighResTimeStamp PaintTimeStamp(SystemCallerGuarantee);
 
 protected:
   ~NotifyPaintEvent() {}
 
 private:
   nsRegion GetRegion(SystemCallerGuarantee);
 
-  nsTArray<nsInvalidateRequestList::Request> mInvalidateRequests;
+  nsTArray<nsRect> mInvalidateRequests;
   uint64_t mTransactionId;
   DOMHighResTimeStamp mTimeStamp;
 };
 
 } // namespace dom
 } // namespace mozilla
 
 // This empties aInvalidateRequests.
 already_AddRefed<mozilla::dom::NotifyPaintEvent>
 NS_NewDOMNotifyPaintEvent(mozilla::dom::EventTarget* aOwner,
                           nsPresContext* aPresContext,
                           mozilla::WidgetEvent* aEvent,
                           mozilla::EventMessage aEventMessage =
                             mozilla::eVoidEvent,
-                          nsInvalidateRequestList* aInvalidateRequests =
-                            nullptr,
+                          nsTArray<nsRect>* aInvalidateRequests = nullptr,
                           uint64_t aTransactionId = 0,
                           DOMHighResTimeStamp aTimeStamp = 0);
 
 #endif // mozilla_dom_NotifyPaintEvent_h_
--- a/dom/events/PaintRequest.cpp
+++ b/dom/events/PaintRequest.cpp
@@ -33,17 +33,17 @@ PaintRequest::WrapObject(JSContext* aCx,
 {
   return PaintRequestBinding::Wrap(aCx, this, aGivenProto);
 }
 
 already_AddRefed<DOMRect>
 PaintRequest::ClientRect()
 {
   RefPtr<DOMRect> clientRect = new DOMRect(this);
-  clientRect->SetLayoutRect(mRequest.mRect);
+  clientRect->SetLayoutRect(mRequest);
   return clientRect.forget();
 }
 
 NS_IMETHODIMP
 PaintRequest::GetClientRect(nsIDOMClientRect** aResult)
 {
   RefPtr<DOMRect> clientRect = ClientRect();
   clientRect.forget(aResult);
--- a/dom/events/PaintRequest.h
+++ b/dom/events/PaintRequest.h
@@ -20,17 +20,16 @@ class DOMRect;
 
 class PaintRequest final : public nsIDOMPaintRequest
                          , public nsWrapperCache
 {
 public:
   explicit PaintRequest(nsIDOMEvent* aParent)
     : mParent(aParent)
   {
-    mRequest.mFlags = 0;
   }
 
   NS_DECL_CYCLE_COLLECTING_ISUPPORTS
   NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(PaintRequest)
   NS_DECL_NSIDOMPAINTREQUEST
 
   virtual JSObject* WrapObject(JSContext* aCx, JS::Handle<JSObject*> aGivenProto) override;
 
@@ -40,24 +39,24 @@ public:
   }
 
   already_AddRefed<DOMRect> ClientRect();
   void GetReason(nsAString& aResult) const
   {
     aResult.AssignLiteral("repaint");
   }
 
-  void SetRequest(const nsInvalidateRequestList::Request& aRequest)
+  void SetRequest(const nsRect& aRequest)
   { mRequest = aRequest; }
 
 private:
   ~PaintRequest() {}
 
   nsCOMPtr<nsIDOMEvent> mParent;
-  nsInvalidateRequestList::Request mRequest;
+  nsRect mRequest;
 };
 
 class PaintRequestList final : public nsISupports,
                                public nsWrapperCache
 {
 public:
   explicit PaintRequestList(nsIDOMEvent *aParent) : mParent(aParent)
   {
--- a/dom/file/MemoryBlobImpl.cpp
+++ b/dom/file/MemoryBlobImpl.cpp
@@ -1,15 +1,16 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "MemoryBlobImpl.h"
+#include "mozilla/IntegerPrintfMacros.h"
 #include "mozilla/SHA1.h"
 #include "nsIIPCSerializableInputStream.h"
 #include "nsPrintfCString.h"
 
 namespace mozilla {
 namespace dom {
 
 // XXXkhuey the input stream that we pass out of a File
@@ -161,21 +162,21 @@ public:
         nsAutoCString digestString;
         for (size_t i = 0; i < sizeof(digest); i++) {
           digestString.AppendPrintf("%02x", digest[i]);
         }
 
         aHandleReport->Callback(
           /* process */ NS_LITERAL_CSTRING(""),
           nsPrintfCString(
-            "explicit/dom/memory-file-data/large/file(length=%llu, sha1=%s)",
+            "explicit/dom/memory-file-data/large/file(length=%" PRIu64 ", sha1=%s)",
             owner->mLength, aAnonymize ? "<anonymized>" : digestString.get()),
           KIND_HEAP, UNITS_BYTES, size,
           nsPrintfCString(
-            "Memory used to back a memory file of length %llu bytes.  The file "
+            "Memory used to back a memory file of length %" PRIu64 " bytes.  The file "
             "has a sha1 of %s.\n\n"
             "Note that the allocator may round up a memory file's length -- "
             "that is, an N-byte memory file may take up more than N bytes of "
             "memory.",
             owner->mLength, digestString.get()),
           aData);
       }
     }
--- a/dom/flyweb/FlyWebPublishedServer.cpp
+++ b/dom/flyweb/FlyWebPublishedServer.cpp
@@ -176,17 +176,17 @@ FlyWebPublishedServerImpl::FlyWebPublish
         AbstractThread::MainThread()))
 {
   LOG_I("FlyWebPublishedServerImpl::FlyWebPublishedServerImpl(%p)", this);
 }
 
 void
 FlyWebPublishedServerImpl::PermissionGranted(bool aGranted)
 {
-  LOG_I("FlyWebPublishedServerImpl::PermissionGranted(%b)", aGranted);
+  LOG_I("FlyWebPublishedServerImpl::PermissionGranted(%d)", aGranted);
   if (!aGranted) {
     PublishedServerStarted(NS_ERROR_FAILURE);
     return;
   }
 
   mHttpServer->Init(-1, Preferences::GetBool("flyweb.use-tls", false), this);
 }
 
--- a/dom/flyweb/HttpServer.cpp
+++ b/dom/flyweb/HttpServer.cpp
@@ -148,17 +148,18 @@ HttpServer::OnSocketAccepted(nsIServerSo
 }
 
 NS_IMETHODIMP
 HttpServer::OnStopListening(nsIServerSocket* aServ,
                             nsresult aStatus)
 {
   MOZ_ASSERT(aServ == mServerSocket || !mServerSocket);
 
-  LOG_I("HttpServer::OnStopListening(%p) - status 0x%lx", this, aStatus);
+  LOG_I("HttpServer::OnStopListening(%p) - status 0x%" PRIx32,
+        this, static_cast<uint32_t>(aStatus));
 
   Close();
 
   return NS_OK;
 }
 
 void
 HttpServer::SendResponse(InternalRequest* aRequest, InternalResponse* aResponse)
@@ -1254,18 +1255,18 @@ HttpServer::Connection::OnOutputStreamRe
       RefPtr<Connection> self = this;
 
       mOutputCopy->
         Then(mServer->mAbstractMainThread,
              __func__,
              [self, this] (nsresult aStatus) {
                MOZ_ASSERT(mOutputBuffers[0].mStream);
                LOG_V("HttpServer::Connection::OnOutputStreamReady(%p) - "
-                     "Sent body. Status 0x%lx",
-                     this, aStatus);
+                     "Sent body. Status 0x%" PRIx32,
+                     this, static_cast<uint32_t>(aStatus));
 
                mOutputBuffers.RemoveElementAt(0);
                mOutputCopy = nullptr;
                OnOutputStreamReady(mOutput);
              },
              [] (bool) { MOZ_ASSERT_UNREACHABLE("Reject unexpected"); });
     }
   }
--- a/dom/html/HTMLMediaElement.cpp
+++ b/dom/html/HTMLMediaElement.cpp
@@ -7226,22 +7226,22 @@ HTMLMediaElement::MarkAsContentSource(Ca
         }
       }
       break;
     }
   }
 
   LOG(LogLevel::Debug,
       ("%p Log VIDEO_AS_CONTENT_SOURCE: visibility = %u, API: '%d' and 'All'",
-       this, isVisible, aAPI));
+       this, isVisible, static_cast<int>(aAPI)));
 
   if (!isVisible) {
     LOG(LogLevel::Debug,
         ("%p Log VIDEO_AS_CONTENT_SOURCE_IN_TREE_OR_NOT: inTree = %u, API: '%d' and 'All'",
-         this, IsInUncomposedDoc(), aAPI));
+         this, IsInUncomposedDoc(), static_cast<int>(aAPI)));
   }
 }
 
 void
 HTMLMediaElement::UpdateCustomPolicyAfterPlayed()
 {
   OpenUnsupportedMediaWithExternalAppIfNeeded();
   if (mAudioChannelWrapper) {
--- a/dom/html/TextTrackManager.cpp
+++ b/dom/html/TextTrackManager.cpp
@@ -7,16 +7,17 @@
 #include "mozilla/dom/TextTrackManager.h"
 #include "mozilla/dom/HTMLMediaElement.h"
 #include "mozilla/dom/HTMLTrackElement.h"
 #include "mozilla/dom/HTMLVideoElement.h"
 #include "mozilla/dom/TextTrack.h"
 #include "mozilla/dom/TextTrackCue.h"
 #include "mozilla/dom/Event.h"
 #include "mozilla/ClearOnShutdown.h"
+#include "mozilla/SizePrintfMacros.h"
 #include "mozilla/Telemetry.h"
 #include "nsComponentManagerUtils.h"
 #include "nsVariant.h"
 #include "nsVideoFrame.h"
 #include "nsIFrame.h"
 #include "nsTArrayHelpers.h"
 #include "nsIWebVTTParserWrapper.h"
 
@@ -153,17 +154,18 @@ TextTrackManager::AddTextTrack(TextTrack
                                TextTrackMode aMode,
                                TextTrackReadyState aReadyState,
                                TextTrackSource aTextTrackSource)
 {
   if (!mMediaElement || !mTextTracks) {
     return nullptr;
   }
   WEBVTT_LOG("%p AddTextTrack",this);
-  WEBVTT_LOGV("AddTextTrack kind %d Label %s Language %s",aKind,
+  WEBVTT_LOGV("AddTextTrack kind %" PRIu32 " Label %s Language %s",
+    static_cast<uint32_t>(aKind),
     NS_ConvertUTF16toUTF8(aLabel).get(), NS_ConvertUTF16toUTF8(aLanguage).get());
   RefPtr<TextTrack> track =
     mTextTracks->AddTextTrack(aKind, aLabel, aLanguage, aMode, aReadyState,
                               aTextTrackSource, CompareTextTracks(mMediaElement));
   AddCues(track);
   ReportTelemetryForTrack(track);
 
   if (aTextTrackSource == TextTrackSource::Track) {
@@ -273,17 +275,17 @@ TextTrackManager::UpdateCueDisplay()
     return;
   }
 
   nsTArray<RefPtr<TextTrackCue> > activeCues;
   mTextTracks->GetShowingCues(activeCues);
 
   if (activeCues.Length() > 0) {
     WEBVTT_LOG("UpdateCueDisplay ProcessCues");
-    WEBVTT_LOGV("UpdateCueDisplay activeCues.Length() %d",activeCues.Length());
+    WEBVTT_LOGV("UpdateCueDisplay activeCues.Length() %" PRIuSIZE, activeCues.Length());
     RefPtr<nsVariantCC> jsCues = new nsVariantCC();
 
     jsCues->SetAsArray(nsIDataType::VTYPE_INTERFACE,
                        &NS_GET_IID(nsIDOMEventTarget),
                        activeCues.Length(),
                        static_cast<void*>(activeCues.Elements()));
     nsPIDOMWindowInner* window = mMediaElement->OwnerDoc()->GetInnerWindow();
     if (window) {
@@ -402,29 +404,31 @@ TextTrackManager::PerformTrackSelection(
                                         uint32_t size)
 {
   nsTArray<TextTrack*> candidates;
   GetTextTracksOfKinds(aTextTrackKinds, size, candidates);
 
   // Step 3: If any TextTracks in candidates are showing then abort these steps.
   for (uint32_t i = 0; i < candidates.Length(); i++) {
     if (candidates[i]->Mode() == TextTrackMode::Showing) {
-      WEBVTT_LOGV("PerformTrackSelection Showing return kind %d",candidates[i]->Kind());
+      WEBVTT_LOGV("PerformTrackSelection Showing return kind %d",
+                  static_cast<int>(candidates[i]->Kind()));
       return;
     }
   }
 
   // Step 4: Honor user preferences for track selection, otherwise, set the
   // first TextTrack in candidates with a default attribute to showing.
   // TODO: Bug 981691 - Honor user preferences for text track selection.
   for (uint32_t i = 0; i < candidates.Length(); i++) {
     if (TrackIsDefault(candidates[i]) &&
         candidates[i]->Mode() == TextTrackMode::Disabled) {
       candidates[i]->SetMode(TextTrackMode::Showing);
-      WEBVTT_LOGV("PerformTrackSelection set Showing kind %d", candidates[i]->Kind());
+      WEBVTT_LOGV("PerformTrackSelection set Showing kind %d",
+                  static_cast<int>(candidates[i]->Kind()));
       return;
     }
   }
 }
 
 void
 TextTrackManager::GetTextTracksOfKinds(TextTrackKind aTextTrackKinds[],
                                        uint32_t size,
--- a/dom/html/nsHTMLDocument.cpp
+++ b/dom/html/nsHTMLDocument.cpp
@@ -91,17 +91,16 @@
 #include "nsIPlaintextEditor.h"
 #include "nsIHTMLEditor.h"
 #include "nsIEditorStyleSheets.h"
 #include "nsIInlineSpellChecker.h"
 #include "nsRange.h"
 #include "mozAutoDocUpdate.h"
 #include "nsCCUncollectableMarker.h"
 #include "nsHtml5Module.h"
-#include "prprf.h"
 #include "mozilla/dom/Element.h"
 #include "mozilla/Preferences.h"
 #include "nsMimeTypes.h"
 #include "nsIRequest.h"
 #include "nsHtml5TreeOpExecutor.h"
 #include "nsHtml5Parser.h"
 #include "nsSandboxFlags.h"
 #include "nsIImageDocument.h"
--- a/dom/indexedDB/ActorsParent.cpp
+++ b/dom/indexedDB/ActorsParent.cpp
@@ -21,16 +21,17 @@
 #include "mozilla/Attributes.h"
 #include "mozilla/AutoRestore.h"
 #include "mozilla/Casting.h"
 #include "mozilla/EndianUtils.h"
 #include "mozilla/LazyIdleThread.h"
 #include "mozilla/Maybe.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/Services.h"
+#include "mozilla/SizePrintfMacros.h"
 #include "mozilla/SnappyCompressOutputStream.h"
 #include "mozilla/SnappyUncompressInputStream.h"
 #include "mozilla/StaticPtr.h"
 #include "mozilla/storage.h"
 #include "mozilla/Unused.h"
 #include "mozilla/UniquePtrExtensions.h"
 #include "mozilla/dom/ContentParent.h"
 #include "mozilla/dom/File.h"
@@ -578,19 +579,19 @@ ClampResultCode(nsresult aResultCode)
 
   switch (aResultCode) {
     case NS_ERROR_FILE_NO_DEVICE_SPACE:
       return NS_ERROR_DOM_INDEXEDDB_QUOTA_ERR;
     case NS_ERROR_STORAGE_CONSTRAINT:
       return NS_ERROR_DOM_INDEXEDDB_CONSTRAINT_ERR;
     default:
 #ifdef DEBUG
-      nsPrintfCString message("Converting non-IndexedDB error code (0x%X) to "
+      nsPrintfCString message("Converting non-IndexedDB error code (0x%" PRIX32 ") to "
                               "NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR",
-                              aResultCode);
+                              static_cast<uint32_t>(aResultCode));
       NS_WARNING(message.get());
 #else
       ;
 #endif
   }
 
   IDB_REPORT_INTERNAL_ERR();
   return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
@@ -4552,17 +4553,17 @@ CreateStorageConnection(nsIFile* aDBFile
 
   if (schemaVersion != kSQLiteSchemaVersion) {
     const bool newDatabase = !schemaVersion;
 
     if (newDatabase) {
       // Set the page size first.
       if (kSQLitePageSizeOverride) {
         rv = connection->ExecuteSimpleSQL(
-          nsPrintfCString("PRAGMA page_size = %lu;", kSQLitePageSizeOverride)
+          nsPrintfCString("PRAGMA page_size = %" PRIu32 ";", kSQLitePageSizeOverride)
         );
         if (NS_WARN_IF(NS_FAILED(rv))) {
           return rv;
         }
       }
 
       // We have to set the auto_vacuum mode before opening a transaction.
       rv = connection->ExecuteSimpleSQL(
@@ -4788,17 +4789,17 @@ CreateStorageConnection(nsIFile* aDBFile
         if (NS_WARN_IF(NS_FAILED(rv))) {
           return rv;
         }
 
         if (journalMode.EqualsLiteral("delete")) {
           // Successfully set to rollback journal mode so changing the page size
           // is possible with a VACUUM.
           rv = connection->ExecuteSimpleSQL(
-            nsPrintfCString("PRAGMA page_size = %lu;", kSQLitePageSizeOverride)
+            nsPrintfCString("PRAGMA page_size = %" PRIu32 ";", kSQLitePageSizeOverride)
           );
           if (NS_WARN_IF(NS_FAILED(rv))) {
             return rv;
           }
 
           // We will need to VACUUM in order to change the page size.
           vacuumNeeded = true;
         } else {
@@ -5719,17 +5720,17 @@ public:
   uint32_t
   SerialNumber() const
   {
     return mSerialNumber;
   }
 
   nsCString GetThreadName() const
   {
-    return nsPrintfCString("IndexedDB #%lu", mSerialNumber);
+    return nsPrintfCString("IndexedDB #%" PRIu32, mSerialNumber);
   }
 
 private:
   ~ThreadRunnable() override;
 
   NS_DECL_NSIRUNNABLE
 };
 
@@ -12616,17 +12617,17 @@ ConnectionPool::ShutdownThread(ThreadInf
   MOZ_ASSERT(mTotalThreadCount);
 
   RefPtr<ThreadRunnable> runnable;
   aThreadInfo.mRunnable.swap(runnable);
 
   nsCOMPtr<nsIThread> thread;
   aThreadInfo.mThread.swap(thread);
 
-  IDB_DEBUG_LOG(("ConnectionPool shutting down thread %lu",
+  IDB_DEBUG_LOG(("ConnectionPool shutting down thread %" PRIu32,
                  runnable->SerialNumber()));
 
   // This should clean up the thread with the profiler.
   MOZ_ALWAYS_SUCCEEDS(thread->Dispatch(runnable.forget(),
                                        NS_DISPATCH_NORMAL));
 
   MOZ_ALWAYS_SUCCEEDS(NS_DispatchToMainThread(
                         NewRunnableMethod(thread, &nsIThread::Shutdown)));
@@ -12717,17 +12718,17 @@ ConnectionPool::ScheduleTransaction(Tran
 
         nsCOMPtr<nsIThread> newThread;
         nsresult rv =
           NS_NewNamedThread(runnable->GetThreadName(),
                             getter_AddRefs(newThread), runnable);
         if (NS_SUCCEEDED(rv)) {
           MOZ_ASSERT(newThread);
 
-          IDB_DEBUG_LOG(("ConnectionPool created thread %lu",
+          IDB_DEBUG_LOG(("ConnectionPool created thread %" PRIu32,
                          runnable->SerialNumber()));
 
           dbInfo->mThreadInfo.mThread.swap(newThread);
           dbInfo->mThreadInfo.mRunnable.swap(runnable);
 
           mTotalThreadCount++;
           created = true;
         } else {
--- a/dom/indexedDB/ProfilerHelpers.h
+++ b/dom/indexedDB/ProfilerHelpers.h
@@ -272,17 +272,17 @@ public:
       eventType = nsDependentString(aDefault);
     }
 
     AppendUTF16toUTF8(eventType, *this);
     Append(kQuote);
   }
 };
 
-inline void
+inline void MOZ_FORMAT_PRINTF(2, 3)
 LoggingHelper(bool aUseProfiler, const char* aFmt, ...)
 {
   MOZ_ASSERT(IndexedDatabaseManager::GetLoggingMode() !=
                IndexedDatabaseManager::Logging_Disabled);
   MOZ_ASSERT(aFmt);
 
   mozilla::LogModule* logModule = IndexedDatabaseManager::GetLoggingModule();
   MOZ_ASSERT(logModule);
--- a/dom/indexedDB/ReportInternalError.cpp
+++ b/dom/indexedDB/ReportInternalError.cpp
@@ -22,15 +22,15 @@ ReportInternalError(const char* aFile, u
   for (const char* p = aFile; *p; ++p) {
     if (*p == '/' && *(p + 1)) {
       aFile = p + 1;
     }
   }
 
   nsContentUtils::LogSimpleConsoleError(
     NS_ConvertUTF8toUTF16(nsPrintfCString(
-                          "IndexedDB %s: %s:%lu", aStr, aFile, aLine)),
+                          "IndexedDB %s: %s:%" PRIu32, aStr, aFile, aLine)),
     "indexedDB");
 }
 
 } // namespace indexedDB
 } // namespace dom
 } // namespace mozilla
--- a/dom/interfaces/base/nsIDOMWindowUtils.idl
+++ b/dom/interfaces/base/nsIDOMWindowUtils.idl
@@ -957,18 +957,16 @@ interface nsIDOMWindowUtils : nsISupport
    * Suppresses/unsuppresses user initiated event handling in window's document
    * and subdocuments.
    *
    * @throw NS_ERROR_DOM_SECURITY_ERR if called without chrome privileges and
    *        NS_ERROR_FAILURE if window doesn't have a document.
    */
   void suppressEventHandling(in boolean aSuppress);
 
-  void clearMozAfterPaintEvents();
-
   /**
    * Disable or enable non synthetic test mouse events on *all* windows.
    *
    * Cannot be accessed from unprivileged context (not content-accessible).
    * Will throw a DOM security error if called without chrome privileges.
    *
    * @param aDisable  If true, disable all non synthetic test mouse events
    *               on all windows.  Otherwise, enable them.
--- a/dom/ipc/ContentParent.cpp
+++ b/dom/ipc/ContentParent.cpp
@@ -414,17 +414,17 @@ ContentParentsMemoryReporter::CollectRep
         channelStr = "closed channel";
       } else {
         channelStr = "open channel";
       }
       numQueuedMessages = channel->Unsound_NumQueuedMessages();
     }
 
     nsPrintfCString path("queued-ipc-messages/content-parent"
-                         "(%s, pid=%d, %s, 0x%p, refcnt=%d)",
+                         "(%s, pid=%d, %s, 0x%p, refcnt=%" PRIuPTR ")",
                          NS_ConvertUTF16toUTF8(friendlyName).get(),
                          cp->Pid(), channelStr,
                          static_cast<nsIContentParent*>(cp), refcnt);
 
     NS_NAMED_LITERAL_CSTRING(desc,
       "The number of unset IPC messages held in this ContentParent's "
       "channel.  A large value here might indicate that we're leaking "
       "messages.  Similarly, a ContentParent object for a process that's no "
--- a/dom/ipc/ProcessPriorityManager.cpp
+++ b/dom/ipc/ProcessPriorityManager.cpp
@@ -529,17 +529,17 @@ ProcessPriorityManagerImpl::GetParticula
   uint64_t cpId = aContentParent->ChildID();
   mParticularManagers.Get(cpId, &pppm);
   if (!pppm) {
     pppm = new ParticularProcessPriorityManager(aContentParent, sFrozen);
     pppm->Init();
     mParticularManagers.Put(cpId, pppm);
 
     FireTestOnlyObserverNotification("process-created",
-      nsPrintfCString("%lld", cpId));
+      nsPrintfCString("%" PRIu64, cpId));
   }
 
   return pppm.forget();
 }
 
 void
 ProcessPriorityManagerImpl::SetProcessPriority(ContentParent* aContentParent,
                                                ProcessPriority aPriority,
@@ -1190,17 +1190,17 @@ void
 ParticularProcessPriorityManager::FireTestOnlyObserverNotification(
   const char* aTopic,
   const nsACString& aData /* = EmptyCString() */)
 {
   if (!ProcessPriorityManagerImpl::TestMode()) {
     return;
   }
 
-  nsAutoCString data(nsPrintfCString("%lld", ChildID()));
+  nsAutoCString data(nsPrintfCString("%" PRIu64, ChildID()));
   if (!aData.IsEmpty()) {
     data.Append(':');
     data.Append(aData);
   }
 
   // ProcessPriorityManagerImpl::GetSingleton() is guaranteed not to return
   // null, since ProcessPriorityManagerImpl is the only class which creates
   // ParticularProcessPriorityManagers.
--- a/dom/ipc/TabChild.cpp
+++ b/dom/ipc/TabChild.cpp
@@ -500,18 +500,18 @@ TabChild::Observe(nsISupports *aSubject,
     if (NS_WARN_IF(NS_FAILED(rv))) {
       return rv;
     }
 
     // In theory a tabChild should contain just 1 top window, but let's double
     // check it comparing the windowID.
     if (window->WindowID() != windowID) {
       MOZ_LOG(AudioChannelService::GetAudioChannelLog(), LogLevel::Debug,
-              ("TabChild, Observe, different windowID, owner ID = %lld, "
-               "ID from wrapper = %lld", window->WindowID(), windowID));
+              ("TabChild, Observe, different windowID, owner ID = %" PRIu64 ", "
+               "ID from wrapper = %" PRIu64, window->WindowID(), windowID));
       return NS_OK;
     }
 
     nsAutoString activeStr(aData);
     bool active = activeStr.EqualsLiteral("active");
     if (active != mAudioChannelsActive[audioChannel]) {
       mAudioChannelsActive[audioChannel] = active;
       Unused << SendAudioChannelActivityNotification(audioChannel, active);
--- a/dom/jsurl/nsJSProtocolHandler.cpp
+++ b/dom/jsurl/nsJSProtocolHandler.cpp
@@ -24,17 +24,16 @@
 #include "nsIPrincipal.h"
 #include "nsIScriptSecurityManager.h"
 #include "nsIInterfaceRequestor.h"
 #include "nsIInterfaceRequestorUtils.h"
 #include "nsIWindowMediator.h"
 #include "nsPIDOMWindow.h"
 #include "nsIConsoleService.h"
 #include "nsXPIDLString.h"
-#include "prprf.h"
 #include "nsEscape.h"
 #include "nsIWebNavigation.h"
 #include "nsIDocShell.h"
 #include "nsIContentViewer.h"
 #include "nsIXPConnect.h"
 #include "nsContentUtils.h"
 #include "nsJSUtils.h"
 #include "nsThreadUtils.h"
--- a/dom/media/ADTSDemuxer.cpp
+++ b/dom/media/ADTSDemuxer.cpp
@@ -7,16 +7,17 @@
 #include "ADTSDemuxer.h"
 
 #include <inttypes.h>
 
 #include "nsAutoPtr.h"
 #include "VideoUtils.h"
 #include "TimeUnits.h"
 #include "prenv.h"
+#include "mozilla/SizePrintfMacros.h"
 
 #ifdef PR_LOGGING
 extern mozilla::LazyLogModule gMediaDemuxerLog;
 #define ADTSLOG(msg, ...) \
   MOZ_LOG(gMediaDemuxerLog, LogLevel::Debug, ("ADTSDemuxer " msg, ##__VA_ARGS__))
 #define ADTSLOGV(msg, ...) \
   MOZ_LOG(gMediaDemuxerLog, LogLevel::Verbose, ("ADTSDemuxer " msg, ##__VA_ARGS__))
 #else
@@ -471,18 +472,18 @@ ADTSTrackDemuxer::FastSeek(const media::
   if (mOffset > firstFrameOffset && StreamLength() > 0) {
     mOffset = std::min(StreamLength() - 1, mOffset);
   }
 
   mFrameIndex = FrameIndexFromOffset(mOffset);
   mParser->EndFrameSession();
 
   ADTSLOG("FastSeek End avgFrameLen=%f mNumParsedFrames=%" PRIu64
-          " mFrameIndex=%" PRId64 " mFirstFrameOffset=%llu mOffset=%" PRIu64
-          " SL=%llu",
+          " mFrameIndex=%" PRId64 " mFirstFrameOffset=%" PRIu64 " mOffset=%" PRIu64
+          " SL=%" PRIu64 "",
           AverageFrameLength(), mNumParsedFrames, mFrameIndex,
           firstFrameOffset, mOffset, StreamLength());
 
   return Duration(mFrameIndex);
 }
 
 media::TimeUnit
 ADTSTrackDemuxer::ScanUntil(const media::TimeUnit& aTime)
@@ -531,17 +532,17 @@ ADTSTrackDemuxer::GetSamples(int32_t aNu
   while (aNumSamples--) {
     RefPtr<MediaRawData> frame(GetNextFrame(FindNextFrame()));
     if (!frame)
       break;
 
     frames->mSamples.AppendElement(frame);
   }
 
-  ADTSLOGV("GetSamples() End mSamples.Size()=%d aNumSamples=%d mOffset=%" PRIu64
+  ADTSLOGV("GetSamples() End mSamples.Size()=%" PRIuSIZE " aNumSamples=%d mOffset=%" PRIu64
            " mNumParsedFrames=%" PRIu64 " mFrameIndex=%" PRId64
            " mTotalFrameLen=%" PRIu64
            " mSamplesPerFrame=%d mSamplesPerSecond=%d "
            "mChannels=%d",
            frames->mSamples.Length(), aNumSamples, mOffset, mNumParsedFrames,
            mFrameIndex, mTotalFrameLen, mSamplesPerFrame, mSamplesPerSecond,
            mChannels);
 
@@ -687,24 +688,24 @@ ADTSTrackDemuxer::FindNextFrame(bool fin
     if (frameHeaderOffset + advance <= frameHeaderOffset) {
       break;
     }
 
     frameHeaderOffset += advance;
   }
 
   if (!foundFrame || !mParser->CurrentFrame().Length()) {
-    ADTSLOG("FindNext() Exit foundFrame=%d mParser->CurrentFrame().Length()=%d ",
+    ADTSLOG("FindNext() Exit foundFrame=%d mParser->CurrentFrame().Length()=%" PRIuSIZE " ",
            foundFrame, mParser->CurrentFrame().Length());
     mParser->Reset();
     return mParser->CurrentFrame();
   }
 
   ADTSLOGV("FindNext() End mOffset=%" PRIu64 " mNumParsedFrames=%" PRIu64
-          " mFrameIndex=%" PRId64 " frameHeaderOffset=%d"
+          " mFrameIndex=%" PRId64 " frameHeaderOffset=%" PRId64
           " mTotalFrameLen=%" PRIu64 " mSamplesPerFrame=%d mSamplesPerSecond=%d"
           " mChannels=%d",
           mOffset, mNumParsedFrames, mFrameIndex, frameHeaderOffset,
           mTotalFrameLen, mSamplesPerFrame, mSamplesPerSecond, mChannels);
 
   return mParser->CurrentFrame();
 }
 
@@ -725,17 +726,18 @@ ADTSTrackDemuxer::SkipNextFrame(const ad
           mSamplesPerFrame, mSamplesPerSecond, mChannels);
 
   return true;
 }
 
 already_AddRefed<MediaRawData>
 ADTSTrackDemuxer::GetNextFrame(const adts::Frame& aFrame)
 {
-  ADTSLOG("GetNext() Begin({mOffset=%" PRId64 " HeaderSize()=%d Length()=%d})",
+  ADTSLOG("GetNext() Begin({mOffset=%" PRId64 " HeaderSize()=%" PRIuSIZE
+          " Length()=%" PRIuSIZE "})",
          aFrame.Offset(), aFrame.Header().HeaderSize(), aFrame.PayloadLength());
   if (!aFrame.IsValid())
     return nullptr;
 
   const int64_t offset = aFrame.PayloadOffset();
   const uint32_t length = aFrame.PayloadLength();
 
   RefPtr<MediaRawData> frame = new MediaRawData();
@@ -744,17 +746,17 @@ ADTSTrackDemuxer::GetNextFrame(const adt
   nsAutoPtr<MediaRawDataWriter> frameWriter(frame->CreateWriter());
   if (!frameWriter->SetSize(length)) {
     ADTSLOG("GetNext() Exit failed to allocated media buffer");
     return nullptr;
   }
 
   const uint32_t read = Read(frameWriter->Data(), offset, length);
   if (read != length) {
-    ADTSLOG("GetNext() Exit read=%u frame->Size()=%u", read, frame->Size());
+    ADTSLOG("GetNext() Exit read=%u frame->Size()=%" PRIuSIZE, read, frame->Size());
     return nullptr;
   }
 
   UpdateState(aFrame);
 
   frame->mTime = Duration(mFrameIndex - 1).ToMicroseconds();
   frame->mDuration = Duration(1).ToMicroseconds();
   frame->mTimecode = frame->mTime;
--- a/dom/media/DecoderDoctorDiagnostics.cpp
+++ b/dom/media/DecoderDoctorDiagnostics.cpp
@@ -829,18 +829,18 @@ DecoderDoctorDiagnostics::GetDescription
         case eUnset:
           break;
         case eWidevineWithNoWMF:
           s += ", Widevine with no WMF";
           break;
       }
       break;
     case eEvent:
-      s = nsPrintfCString("event domain %s result=%u",
-                          EventDomainString(mEvent.mDomain), mEvent.mResult);
+      s = nsPrintfCString("event domain %s result=%" PRIu32,
+                          EventDomainString(mEvent.mDomain), static_cast<uint32_t>(mEvent.mResult));
       break;
     default:
       MOZ_ASSERT_UNREACHABLE("Unexpected DiagnosticsType");
       s = "?";
       break;
   }
   return s;
 }
--- a/dom/media/Latency.cpp
+++ b/dom/media/Latency.cpp
@@ -185,21 +185,21 @@ AsyncLatencyLogger::Observe(nsISupports*
 }
 
 // aID is a sub-identifier (in particular a specific MediaStramTrack)
 void AsyncLatencyLogger::WriteLog(LatencyLogIndex aIndex, uint64_t aID, int64_t aValue,
                                   TimeStamp aTimeStamp)
 {
   if (aTimeStamp.IsNull()) {
     MOZ_LOG(GetLatencyLog(), LogLevel::Debug,
-      ("Latency: %s,%llu,%lld,%lld",
+      ("Latency: %s,%" PRIu64 ",%" PRId64 ",%" PRId64,
        LatencyLogIndex2Strings[aIndex], aID, GetTimeStamp(), aValue));
   } else {
     MOZ_LOG(GetLatencyLog(), LogLevel::Debug,
-      ("Latency: %s,%llu,%lld,%lld,%lld",
+      ("Latency: %s,%" PRIu64 ",%" PRId64 ",%" PRId64 ",%" PRId64,
        LatencyLogIndex2Strings[aIndex], aID, GetTimeStamp(), aValue,
        static_cast<int64_t>((aTimeStamp - gAsyncLogger->mStart).ToMilliseconds())));
   }
 }
 
 int64_t AsyncLatencyLogger::GetTimeStamp()
 {
   TimeDuration t = TimeStamp::Now() - mStart;
--- a/dom/media/MP3Demuxer.cpp
+++ b/dom/media/MP3Demuxer.cpp
@@ -6,16 +6,17 @@
 
 #include "MP3Demuxer.h"
 
 #include <inttypes.h>
 #include <algorithm>
 
 #include "mozilla/Assertions.h"
 #include "mozilla/EndianUtils.h"
+#include "mozilla/SizePrintfMacros.h"
 #include "nsAutoPtr.h"
 #include "VideoUtils.h"
 #include "TimeUnits.h"
 #include "prenv.h"
 
 #ifdef PR_LOGGING
 extern mozilla::LazyLogModule gMediaDemuxerLog;
 #define MP3LOG(msg, ...) \
@@ -233,18 +234,18 @@ MP3TrackDemuxer::FastSeek(const TimeUnit
 
   if (mOffset > mFirstFrameOffset && StreamLength() > 0) {
     mOffset = std::min(StreamLength() - 1, mOffset);
   }
 
   mParser.EndFrameSession();
 
   MP3LOG("FastSeek End TOC=%d avgFrameLen=%f mNumParsedFrames=%" PRIu64
-         " mFrameIndex=%" PRId64 " mFirstFrameOffset=%llu mOffset=%" PRIu64
-         " SL=%llu NumBytes=%u",
+         " mFrameIndex=%" PRId64 " mFirstFrameOffset=%" PRId64 " mOffset=%" PRIu64
+         " SL=%" PRId64 " NumBytes=%u",
          vbr.IsTOCPresent(), AverageFrameLength(), mNumParsedFrames, mFrameIndex,
          mFirstFrameOffset, mOffset, StreamLength(), vbr.NumBytes().valueOr(0));
 
   return Duration(mFrameIndex);
 }
 
 TimeUnit
 MP3TrackDemuxer::ScanUntil(const TimeUnit& aTime)
@@ -304,17 +305,17 @@ MP3TrackDemuxer::GetSamples(int32_t aNum
     RefPtr<MediaRawData> frame(GetNextFrame(FindNextFrame()));
     if (!frame) {
       break;
     }
 
     frames->mSamples.AppendElement(frame);
   }
 
-  MP3LOGV("GetSamples() End mSamples.Size()=%d aNumSamples=%d mOffset=%" PRIu64
+  MP3LOGV("GetSamples() End mSamples.Size()=%" PRIuSIZE " aNumSamples=%d mOffset=%" PRIu64
           " mNumParsedFrames=%" PRIu64 " mFrameIndex=%" PRId64
           " mTotalFrameLen=%" PRIu64 " mSamplesPerFrame=%d mSamplesPerSecond=%d "
           "mChannels=%d",
           frames->mSamples.Length(), aNumSamples, mOffset, mNumParsedFrames,
           mFrameIndex, mTotalFrameLen, mSamplesPerFrame, mSamplesPerSecond,
           mChannels);
 
   if (frames->mSamples.IsEmpty()) {
@@ -546,17 +547,17 @@ MP3TrackDemuxer::FindNextFrame()
 
   if (!foundFrame || !mParser.CurrentFrame().Length()) {
     MP3LOG("FindNext() Exit foundFrame=%d mParser.CurrentFrame().Length()=%d ",
            foundFrame, mParser.CurrentFrame().Length());
     return { 0, 0 };
   }
 
   MP3LOGV("FindNext() End mOffset=%" PRIu64 " mNumParsedFrames=%" PRIu64
-          " mFrameIndex=%" PRId64 " frameHeaderOffset=%d"
+          " mFrameIndex=%" PRId64 " frameHeaderOffset=%" PRId64
           " mTotalFrameLen=%" PRIu64 " mSamplesPerFrame=%d mSamplesPerSecond=%d"
           " mChannels=%d",
           mOffset, mNumParsedFrames, mFrameIndex, frameHeaderOffset,
           mTotalFrameLen, mSamplesPerFrame, mSamplesPerSecond, mChannels);
 
   return { frameHeaderOffset, frameHeaderOffset + mParser.CurrentFrame().Length() };
 }
 
@@ -597,17 +598,17 @@ MP3TrackDemuxer::GetNextFrame(const Medi
     MP3LOG("GetNext() Exit failed to allocated media buffer");
     return nullptr;
   }
 
   const uint32_t read =
     Read(frameWriter->Data(), frame->mOffset, frame->Size());
 
   if (read != aRange.Length()) {
-    MP3LOG("GetNext() Exit read=%u frame->Size()=%u", read, frame->Size());
+    MP3LOG("GetNext() Exit read=%u frame->Size()=%" PRIuSIZE, read, frame->Size());
     return nullptr;
   }
 
   UpdateState(aRange);
 
   frame->mTime = Duration(mFrameIndex - 1).ToMicroseconds();
   frame->mDuration = Duration(1).ToMicroseconds();
   frame->mTimecode = frame->mTime;
@@ -831,17 +832,17 @@ FrameParser::Parse(ByteReader* aReader, 
       // ID3 tag found, skip past it.
       const uint32_t skipSize = tagSize - ID3Parser::ID3Header::SIZE;
 
       if (skipSize > aReader->Remaining()) {
         // Skipping across the ID3v2 tag would take us past the end of the
         // buffer, therefore we return immediately and let the calling function
         // handle skipping the rest of the tag.
         MP3LOGV("ID3v2 tag detected, size=%d,"
-                " needing to skip %d bytes past the current buffer",
+                " needing to skip %" PRIuSIZE " bytes past the current buffer",
                 tagSize, skipSize - aReader->Remaining());
         *aBytesToSkip = skipSize - aReader->Remaining();
         return false;
       }
       MP3LOGV("ID3v2 tag detected, size=%d", tagSize);
       aReader->Read(skipSize);
     } else {
       // No ID3v2 tag found, rewinding reader in order to search for a MPEG
@@ -1243,17 +1244,17 @@ FrameParser::VBRHeader::ParseVBRI(ByteRe
 }
 
 bool
 FrameParser::VBRHeader::Parse(ByteReader* aReader)
 {
   const bool rv = ParseVBRI(aReader) || ParseXing(aReader);
   if (rv) {
     MP3LOG("VBRHeader::Parse found valid VBR/CBR header: type=%s"
-           " NumAudioFrames=%u NumBytes=%u Scale=%u TOC-size=%u",
+           " NumAudioFrames=%u NumBytes=%u Scale=%u TOC-size=%" PRIuSIZE,
            vbr_header::TYPE_STR[Type()], NumAudioFrames().valueOr(0),
            NumBytes().valueOr(0), Scale().valueOr(0), mTOC.size());
   }
   return rv;
 }
 
 // FrameParser::Frame
 
--- a/dom/media/MediaCache.cpp
+++ b/dom/media/MediaCache.cpp
@@ -1269,17 +1269,18 @@ MediaCache::Update()
         for (uint32_t j = 0; j < i; ++j) {
           MediaCacheStream* other = mStreams[j];
           if (other->mResourceID == stream->mResourceID &&
               !other->mClosed && !other->mClient->IsSuspended() &&
               other->mChannelOffset/BLOCK_SIZE == desiredOffset/BLOCK_SIZE) {
             // This block is already going to be read by the other stream.
             // So don't try to read it from this stream as well.
             enableReading = false;
-            CACHE_LOG(LogLevel::Debug, ("Stream %p waiting on same block (%lld) from stream %p",
+            CACHE_LOG(LogLevel::Debug, ("Stream %p waiting on same block (%"
+                                        PRId64 ") from stream %p",
                                      stream, desiredOffset/BLOCK_SIZE, other));
             break;
           }
         }
       }
 
       if (stream->mChannelOffset != desiredOffset && enableReading) {
         // We need to seek now.
@@ -1832,18 +1833,18 @@ MediaCacheStream::FlushPartialBlockInter
                                             ReentrantMonitorAutoEnter& aReentrantMonitor)
 {
   NS_ASSERTION(NS_IsMainThread(), "Only call on main thread");
 
   int32_t blockOffset = int32_t(mChannelOffset%BLOCK_SIZE);
   if (blockOffset > 0) {
     CACHE_LOG(LogLevel::Debug,
               ("Stream %p writing partial block: [%d] bytes; "
-               "mStreamOffset [%lld] mChannelOffset[%lld] mStreamLength [%lld] "
-               "notifying: [%s]",
+               "mStreamOffset [%" PRId64 "] mChannelOffset[%"
+               PRId64 "] mStreamLength [%" PRId64 "] notifying: [%s]",
                this, blockOffset, mStreamOffset, mChannelOffset, mStreamLength,
                aNotifyAll ? "yes" : "no"));
 
     // Write back the partial block
     memset(reinterpret_cast<char*>(mPartialBlockBuffer.get()) + blockOffset, 0,
            BLOCK_SIZE - blockOffset);
     gMediaCache->AllocateAndWriteBlock(this, mPartialBlockBuffer.get(),
         mMetadataInPartialBlockBuffer ? MODE_METADATA : MODE_PLAYBACK);
@@ -2300,17 +2301,17 @@ MediaCacheStream::Read(char* aBuffer, ui
     count += bytes;
   }
 
   if (count > 0) {
     // Some data was read, so queue an update since block priorities may
     // have changed
     gMediaCache->QueueUpdate();
   }
-  CACHE_LOG(LogLevel::Debug, ("Stream %p Read at %lld count=%d", this, streamOffset-count, count));
+  CACHE_LOG(LogLevel::Debug, ("Stream %p Read at %" PRId64 " count=%d", this, streamOffset-count, count));
   *aBytes = count;
   mStreamOffset = streamOffset;
   return NS_OK;
 }
 
 nsresult
 MediaCacheStream::ReadAt(int64_t aOffset, char* aBuffer,
                          uint32_t aCount, uint32_t* aBytes)
--- a/dom/media/MediaDecoder.cpp
+++ b/dom/media/MediaDecoder.cpp
@@ -1114,17 +1114,17 @@ MediaDecoder::NotifyBytesDownloaded()
 }
 
 void
 MediaDecoder::NotifyDownloadEnded(nsresult aStatus)
 {
   MOZ_ASSERT(NS_IsMainThread());
   MOZ_DIAGNOSTIC_ASSERT(!IsShutdown());
 
-  DECODER_LOG("NotifyDownloadEnded, status=%x", aStatus);
+  DECODER_LOG("NotifyDownloadEnded, status=%" PRIx32, static_cast<uint32_t>(aStatus));
 
   if (aStatus == NS_BINDING_ABORTED) {
     // Download has been cancelled by user.
     GetOwner()->LoadAborted();
     return;
   }
 
   UpdatePlaybackRate();
--- a/dom/media/MediaDecoderReader.cpp
+++ b/dom/media/MediaDecoderReader.cpp
@@ -220,17 +220,18 @@ MediaDecoderReader::AsyncReadMetadata()
   metadata->mInfo.AssertValid();
 
   // Update the buffer ranges before resolving the metadata promise. Bug 1320258.
   UpdateBuffered();
 
   // We're not waiting for anything. If we didn't get the metadata, that's an
   // error.
   if (NS_FAILED(rv) || !metadata->mInfo.HasValidMedia()) {
-    DECODER_WARN("ReadMetadata failed, rv=%x HasValidMedia=%d", rv, metadata->mInfo.HasValidMedia());
+    DECODER_WARN("ReadMetadata failed, rv=%" PRIx32 " HasValidMedia=%d",
+                 static_cast<uint32_t>(rv), metadata->mInfo.HasValidMedia());
     return MetadataPromise::CreateAndReject(NS_ERROR_DOM_MEDIA_METADATA_ERR, __func__);
   }
 
   // Success!
   return MetadataPromise::CreateAndResolve(metadata, __func__);
 }
 
 class ReRequestVideoWithSkipTask : public Runnable
--- a/dom/media/MediaDecoderStateMachine.cpp
+++ b/dom/media/MediaDecoderStateMachine.cpp
@@ -21,16 +21,17 @@
 #include "mediasink/OutputStreamManager.h"
 #include "mediasink/VideoSink.h"
 #include "mozilla/DebugOnly.h"
 #include "mozilla/Logging.h"
 #include "mozilla/mozalloc.h"
 #include "mozilla/MathAlgorithms.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/SharedThreadPool.h"
+#include "mozilla/SizePrintfMacros.h"
 #include "mozilla/Sprintf.h"
 #include "mozilla/TaskQueue.h"
 
 #include "nsComponentManagerUtils.h"
 #include "nsContentUtils.h"
 #include "nsIEventTarget.h"
 #include "nsITimer.h"
 #include "nsPrintfCString.h"
@@ -797,18 +798,18 @@ private:
       mMaster->mLowAudioThresholdUsecs =
         std::min(adjustedTime, mMaster->mAmpleAudioThresholdUsecs);
 
       mMaster->mAmpleAudioThresholdUsecs =
         std::max(THRESHOLD_FACTOR * mMaster->mLowAudioThresholdUsecs,
                  mMaster->mAmpleAudioThresholdUsecs);
 
       SLOG("Slow video decode, set "
-           "mLowAudioThresholdUsecs=%lld "
-           "mAmpleAudioThresholdUsecs=%lld",
+           "mLowAudioThresholdUsecs=%" PRId64
+           " mAmpleAudioThresholdUsecs=%" PRId64,
            mMaster->mLowAudioThresholdUsecs,
            mMaster->mAmpleAudioThresholdUsecs);
     }
   }
 
   bool DonePrerollingAudio()
   {
     return !mMaster->IsAudioDecoding()
@@ -1352,36 +1353,36 @@ private:
 
     return NS_OK;
   }
 
   nsresult DropVideoUpToSeekTarget(MediaData* aSample)
   {
     RefPtr<VideoData> video(aSample->As<VideoData>());
     MOZ_ASSERT(video);
-    SLOG("DropVideoUpToSeekTarget() frame [%lld, %lld]",
+    SLOG("DropVideoUpToSeekTarget() frame [%" PRId64 ", %" PRId64 "]",
          video->mTime, video->GetEndTime());
     const int64_t target = mSeekJob.mTarget->GetTime().ToMicroseconds();
 
     // If the frame end time is less than the seek target, we won't want
     // to display this frame after the seek, so discard it.
     if (target >= video->GetEndTime()) {
-      SLOG("DropVideoUpToSeekTarget() pop video frame [%lld, %lld] target=%lld",
+      SLOG("DropVideoUpToSeekTarget() pop video frame [%" PRId64 ", %" PRId64 "] target=%" PRId64,
            video->mTime, video->GetEndTime(), target);
       mFirstVideoFrameAfterSeek = video;
     } else {
       if (target >= video->mTime && video->GetEndTime() >= target) {
         // The seek target lies inside this frame's time slice. Adjust the
         // frame's start time to match the seek target.
         video->UpdateTimestamp(target);
       }
       mFirstVideoFrameAfterSeek = nullptr;
 
-      SLOG("DropVideoUpToSeekTarget() found video frame [%lld, %lld] "
-           "containing target=%lld",
+      SLOG("DropVideoUpToSeekTarget() found video frame [%" PRId64 ", %" PRId64 "] "
+           "containing target=%" PRId64,
            video->mTime, video->GetEndTime(), target);
 
       MOZ_ASSERT(VideoQueue().GetSize() == 0,
                  "Should be the 1st sample after seeking");
       mMaster->PushVideo(video);
       mDoneVideoSeeking = true;
     }
 
@@ -1906,17 +1907,17 @@ public:
     MOZ_DIAGNOSTIC_ASSERT(false, "Already shutting down.");
   }
 };
 
 RefPtr<MediaDecoder::SeekPromise>
 MediaDecoderStateMachine::
 StateObject::HandleSeek(SeekTarget aTarget)
 {
-  SLOG("Changed state to SEEKING (to %lld)", aTarget.GetTime().ToMicroseconds());
+  SLOG("Changed state to SEEKING (to %" PRId64 ")", aTarget.GetTime().ToMicroseconds());
   SeekJob seekJob;
   seekJob.mTarget = Some(aTarget);
   return SetSeekingState(Move(seekJob), EventVisibility::Observable);
 }
 
 RefPtr<ShutdownPromise>
 MediaDecoderStateMachine::
 StateObject::HandleShutdown()
@@ -2367,17 +2368,17 @@ SeekingState::SeekCompleted()
   if (!target.IsVideoOnly()) {
     // Don't update playback position for video-only seek.
     // Otherwise we might have |newCurrentTime > mMediaSink->GetPosition()|
     // and fail the assertion in GetClock() since we didn't stop MediaSink.
     mMaster->UpdatePlaybackPositionInternal(newCurrentTime);
   }
 
   // Try to decode another frame to detect if we're at the end...
-  SLOG("Seek completed, mCurrentPosition=%lld",
+  SLOG("Seek completed, mCurrentPosition=%" PRId64,
        mMaster->mCurrentPosition.Ref());
 
   if (mMaster->VideoQueue().PeekFront()) {
     mMaster->mMediaSink->Redraw(Info().mVideo);
     mMaster->mOnPlaybackEvent.Notify(MediaEventType::Invalidate);
   }
 
   SetState<DecodingState>();
@@ -2864,17 +2865,17 @@ void MediaDecoderStateMachine::MaybeStar
     mMediaSink->SetPlaying(true);
     MOZ_ASSERT(IsPlaying());
   }
 }
 
 void MediaDecoderStateMachine::UpdatePlaybackPositionInternal(int64_t aTime)
 {
   MOZ_ASSERT(OnTaskQueue());
-  SAMPLE_LOG("UpdatePlaybackPositionInternal(%lld)", aTime);
+  SAMPLE_LOG("UpdatePlaybackPositionInternal(%" PRId64 ")", aTime);
 
   mCurrentPosition = aTime;
   NS_ASSERTION(mCurrentPosition >= 0, "CurrentTime should be positive!");
   mObservedDuration = std::max(mObservedDuration.Ref(),
                                TimeUnit::FromMicroseconds(mCurrentPosition.Ref()));
 }
 
 void MediaDecoderStateMachine::UpdatePlaybackPosition(int64_t aTime)
@@ -3082,33 +3083,33 @@ void MediaDecoderStateMachine::StopMedia
 
 void
 MediaDecoderStateMachine::RequestAudioData()
 {
   MOZ_ASSERT(OnTaskQueue());
   MOZ_ASSERT(IsAudioDecoding());
   MOZ_ASSERT(!IsRequestingAudioData());
   MOZ_ASSERT(!IsWaitingAudioData());
-  SAMPLE_LOG("Queueing audio task - queued=%i, decoder-queued=%o",
+  SAMPLE_LOG("Queueing audio task - queued=%" PRIuSIZE ", decoder-queued=%" PRIuSIZE,
              AudioQueue().GetSize(), mReader->SizeOfAudioQueueInFrames());
 
   mReader->RequestAudioData()->Then(
     OwnerThread(), __func__,
     [this] (MediaData* aAudio) {
       MOZ_ASSERT(aAudio);
       mAudioDataRequest.Complete();
       // audio->GetEndTime() is not always mono-increasing in chained ogg.
       mDecodedAudioEndTime =
         std::max(aAudio->GetEndTime(), mDecodedAudioEndTime);
-      SAMPLE_LOG("OnAudioDecoded [%lld,%lld]", aAudio->mTime,
+      SAMPLE_LOG("OnAudioDecoded [%" PRId64 ",%" PRId64 "]", aAudio->mTime,
                  aAudio->GetEndTime());
       mStateObj->HandleAudioDecoded(aAudio);
     },
     [this] (const MediaResult& aError) {
-      SAMPLE_LOG("OnAudioNotDecoded aError=%u", aError.Code());
+      SAMPLE_LOG("OnAudioNotDecoded aError=%" PRIu32, static_cast<uint32_t>(aError.Code()));
       mAudioDataRequest.Complete();
       switch (aError.Code()) {
         case NS_ERROR_DOM_MEDIA_WAITING_FOR_DATA:
           mStateObj->HandleWaitingForAudio();
           break;
         case NS_ERROR_DOM_MEDIA_CANCELED:
           mStateObj->HandleAudioCanceled();
           break;
@@ -3125,35 +3126,36 @@ void
 MediaDecoderStateMachine::RequestVideoData(bool aSkipToNextKeyframe,
                                            const media::TimeUnit& aCurrentTime)
 {
   MOZ_ASSERT(OnTaskQueue());
   MOZ_ASSERT(IsVideoDecoding());
   MOZ_ASSERT(!IsRequestingVideoData());
   MOZ_ASSERT(!IsWaitingVideoData());
   SAMPLE_LOG(
-    "Queueing video task - queued=%i, decoder-queued=%o, skip=%i, time=%lld",
+    "Queueing video task - queued=%" PRIuSIZE ", decoder-queued=%" PRIoSIZE
+    ", skip=%i, time=%" PRId64,
     VideoQueue().GetSize(), mReader->SizeOfVideoQueueInFrames(),
     aSkipToNextKeyframe, aCurrentTime.ToMicroseconds());
 
   TimeStamp videoDecodeStartTime = TimeStamp::Now();
   mReader->RequestVideoData(aSkipToNextKeyframe, aCurrentTime)->Then(
     OwnerThread(), __func__,
     [this, videoDecodeStartTime] (MediaData* aVideo) {
       MOZ_ASSERT(aVideo);
       mVideoDataRequest.Complete();
       // Handle abnormal or negative timestamps.
       mDecodedVideoEndTime =
         std::max(mDecodedVideoEndTime, aVideo->GetEndTime());
-      SAMPLE_LOG("OnVideoDecoded [%lld,%lld]", aVideo->mTime,
+      SAMPLE_LOG("OnVideoDecoded [%" PRId64 ",%" PRId64 "]", aVideo->mTime,
                  aVideo->GetEndTime());
       mStateObj->HandleVideoDecoded(aVideo, videoDecodeStartTime);
     },
     [this] (const MediaResult& aError) {
-      SAMPLE_LOG("OnVideoNotDecoded aError=%u", aError.Code());
+      SAMPLE_LOG("OnVideoNotDecoded aError=%" PRIu32 , static_cast<uint32_t>(aError.Code()));
       mVideoDataRequest.Complete();
       switch (aError.Code()) {
         case NS_ERROR_DOM_MEDIA_WAITING_FOR_DATA:
           mStateObj->HandleWaitingForVideo();
           break;
         case NS_ERROR_DOM_MEDIA_CANCELED:
           mStateObj->HandleVideoCanceled();
           break;
@@ -3355,17 +3357,17 @@ void
 MediaDecoderStateMachine::FinishDecodeFirstFrame()
 {
   MOZ_ASSERT(OnTaskQueue());
   MOZ_ASSERT(!mSentFirstFrameLoadedEvent);
   DECODER_LOG("FinishDecodeFirstFrame");
 
   mMediaSink->Redraw(Info().mVideo);
 
-  DECODER_LOG("Media duration %lld, "
+  DECODER_LOG("Media duration %" PRId64 ", "
               "transportSeekable=%d, mediaSeekable=%d",
               Duration().ToMicroseconds(), mResource->IsTransportSeekable(),
               mMediaSeekable);
 
   // Get potentially updated metadata
   mReader->ReadUpdatedMetadata(mInfo.ptr());
 
   EnqueueFirstFrameLoadedEvent();
@@ -3749,21 +3751,21 @@ uint32_t MediaDecoderStateMachine::GetAm
          : std::max<uint32_t>(sVideoQueueDefaultSize, MIN_VIDEO_QUEUE_SIZE);
 }
 
 nsCString
 MediaDecoderStateMachine::GetDebugInfo()
 {
   MOZ_ASSERT(OnTaskQueue());
   return nsPrintfCString(
-           "GetMediaTime=%lld GetClock=%lld mMediaSink=%p "
+           "GetMediaTime=%" PRId64 " GetClock=%" PRId64 " mMediaSink=%p "
            "state=%s mPlayState=%d mSentFirstFrameLoadedEvent=%d IsPlaying=%d "
-           "mAudioStatus=%s mVideoStatus=%s mDecodedAudioEndTime=%lld "
-           "mDecodedVideoEndTime=%lld "
-           "mAudioCompleted=%d mVideoCompleted=%d ",
+           "mAudioStatus=%s mVideoStatus=%s mDecodedAudioEndTime=%" PRId64
+           " mDecodedVideoEndTime=%" PRId64
+           " mAudioCompleted=%d mVideoCompleted=%d ",
            GetMediaTime(), mMediaSink->IsStarted() ? GetClock() : -1,
            mMediaSink.get(), ToStateStr(), mPlayState.Ref(),
            mSentFirstFrameLoadedEvent, IsPlaying(), AudioRequestStatus(),
            VideoRequestStatus(), mDecodedAudioEndTime, mDecodedVideoEndTime,
            mAudioCompleted, mVideoCompleted)
          + mStateObj->GetDebugInfo() + nsCString("\n")
          + mMediaSink->GetDebugInfo();
 }
--- a/dom/media/MediaFormatReader.cpp
+++ b/dom/media/MediaFormatReader.cpp
@@ -1,15 +1,16 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim:set ts=2 sw=2 sts=2 et cindent: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "AutoTaskQueue.h"
+#include "mozilla/SizePrintfMacros.h"
 #include "Layers.h"
 #include "MediaData.h"
 #include "MediaInfo.h"
 #include "MediaFormatReader.h"
 #include "MediaPrefs.h"
 #include "MediaResource.h"
 #include "VideoUtils.h"
 #include "VideoFrameContainer.h"
@@ -1321,17 +1322,17 @@ MediaFormatReader::RequestVideoData(bool
 {
   MOZ_ASSERT(OnTaskQueue());
   MOZ_DIAGNOSTIC_ASSERT(mSeekPromise.IsEmpty(),
                         "No sample requests allowed while seeking");
   MOZ_DIAGNOSTIC_ASSERT(!mVideo.HasPromise(), "No duplicate sample requests");
   MOZ_DIAGNOSTIC_ASSERT(!mVideo.mSeekRequest.Exists()
                         || mVideo.mTimeThreshold.isSome());
   MOZ_DIAGNOSTIC_ASSERT(!IsSeeking(), "called mid-seek");
-  LOGV("RequestVideoData(%d, %lld)", aSkipToNextKeyframe, aTimeThreshold);
+  LOGV("RequestVideoData(%d, %" PRId64 ")", aSkipToNextKeyframe, aTimeThreshold);
 
   if (!HasVideo()) {
     LOG("called with no video track");
     return MediaDataPromise::CreateAndReject(NS_ERROR_DOM_MEDIA_FATAL_ERR,
                                              __func__);
   }
 
   if (IsSeeking()) {
@@ -1362,18 +1363,19 @@ MediaFormatReader::RequestVideoData(bool
 
   return p;
 }
 
 void
 MediaFormatReader::OnDemuxFailed(TrackType aTrack, const MediaResult& aError)
 {
   MOZ_ASSERT(OnTaskQueue());
-  LOG("Failed to demux %s, failure:%u",
-      aTrack == TrackType::kVideoTrack ? "video" : "audio", aError.Code());
+  LOG("Failed to demux %s, failure:%" PRIu32,
+      aTrack == TrackType::kVideoTrack ? "video" : "audio",
+      static_cast<uint32_t>(aError.Code()));
   auto& decoder = GetDecoderData(aTrack);
   decoder.mDemuxRequest.Complete();
   switch (aError.Code()) {
     case NS_ERROR_DOM_MEDIA_END_OF_STREAM:
       if (!decoder.mWaitingForData) {
         decoder.RequestDrain();
       }
       NotifyEndOfStream(aTrack);
@@ -1416,17 +1418,17 @@ MediaFormatReader::DoDemuxVideo()
           &MediaFormatReader::OnVideoDemuxFailed)
    ->Track(mVideo.mDemuxRequest);
 }
 
 void
 MediaFormatReader::OnVideoDemuxCompleted(
   RefPtr<MediaTrackDemuxer::SamplesHolder> aSamples)
 {
-  LOGV("%d video samples demuxed (sid:%d)",
+  LOGV("%" PRIuSIZE " video samples demuxed (sid:%d)",
        aSamples->mSamples.Length(),
        aSamples->mSamples[0]->mTrackInfo
        ? aSamples->mSamples[0]->mTrackInfo->GetID()
        : 0);
   mVideo.mDemuxRequest.Complete();
   mVideo.mQueuedSamples.AppendElements(aSamples->mSamples);
   ScheduleUpdate(TrackInfo::kVideoTrack);
 }
@@ -1489,34 +1491,34 @@ MediaFormatReader::DoDemuxAudio()
           &MediaFormatReader::OnAudioDemuxFailed)
    ->Track(mAudio.mDemuxRequest);
 }
 
 void
 MediaFormatReader::OnAudioDemuxCompleted(
   RefPtr<MediaTrackDemuxer::SamplesHolder> aSamples)
 {
-  LOGV("%d audio samples demuxed (sid:%d)",
+  LOGV("%" PRIuSIZE " audio samples demuxed (sid:%d)",
        aSamples->mSamples.Length(),
        aSamples->mSamples[0]->mTrackInfo
        ? aSamples->mSamples[0]->mTrackInfo->GetID()
        : 0);
   mAudio.mDemuxRequest.Complete();
   mAudio.mQueuedSamples.AppendElements(aSamples->mSamples);
   ScheduleUpdate(TrackInfo::kAudioTrack);
 }
 
 void
 MediaFormatReader::NotifyNewOutput(
   TrackType aTrack, const MediaDataDecoder::DecodedData& aResults)
 {
   MOZ_ASSERT(OnTaskQueue());
   auto& decoder = GetDecoderData(aTrack);
   for (auto& sample : aResults) {
-    LOGV("Received new %s sample time:%lld duration:%lld",
+    LOGV("Received new %s sample time:%" PRId64 " duration:%" PRId64,
         TrackTypeToStr(aTrack), sample->mTime, sample->mDuration);
     decoder.mOutput.AppendElement(sample);
     decoder.mNumSamplesOutput++;
     decoder.mNumOfConsecutiveError = 0;
   }
   LOG("Done processing new %s samples", TrackTypeToStr(aTrack));
   ScheduleUpdate(aTrack);
 }
@@ -1798,24 +1800,24 @@ MediaFormatReader::HandleDemuxedSamples(
       if (sample->mKeyframe) {
         ScheduleUpdate(aTrack);
       } else {
         TimeInterval time =
           TimeInterval(TimeUnit::FromMicroseconds(sample->mTime),
                        TimeUnit::FromMicroseconds(sample->GetEndTime()));
         InternalSeekTarget seekTarget =
           decoder.mTimeThreshold.refOr(InternalSeekTarget(time, false));
-        LOG("Stream change occurred on a non-keyframe. Seeking to:%lld",
+        LOG("Stream change occurred on a non-keyframe. Seeking to:%" PRId64,
             sample->mTime);
         InternalSeek(aTrack, seekTarget);
       }
       return;
     }
 
-    LOGV("Input:%lld (dts:%lld kf:%d)",
+    LOGV("Input:%" PRId64 " (dts:%" PRId64 " kf:%d)",
          sample->mTime, sample->mTimecode, sample->mKeyframe);
     decoder.mNumSamplesInput++;
     decoder.mSizeOfQueue++;
     if (aTrack == TrackInfo::kVideoTrack) {
       aA.mStats.mParsedFrames++;
     }
 
     DecodeDemuxedSamples(aTrack, sample);
@@ -1979,17 +1981,17 @@ MediaFormatReader::Update(TrackType aTra
            output->mKeyframe);
       decoder.mOutput.RemoveElementAt(0);
       decoder.mSizeOfQueue -= 1;
     }
   }
 
   while (decoder.mOutput.Length()
          && decoder.mOutput[0]->mType == MediaData::NULL_DATA) {
-    LOGV("Dropping null data. Time: %lld", decoder.mOutput[0]->mTime);
+    LOGV("Dropping null data. Time: %" PRId64, decoder.mOutput[0]->mTime);
     decoder.mOutput.RemoveElementAt(0);
     decoder.mSizeOfQueue -= 1;
   }
 
   if (decoder.HasPromise()) {
     needOutput = true;
     if (decoder.mOutput.Length()) {
       RefPtr<MediaData> output = decoder.mOutput[0];
@@ -2034,17 +2036,17 @@ MediaFormatReader::Update(TrackType aTra
         decoder.RejectPromise(NS_ERROR_DOM_MEDIA_END_OF_STREAM, __func__);
       } else if (decoder.mWaitingForData) {
         if (decoder.mDrainState == DrainState::DrainCompleted
             && decoder.mLastSampleTime
             && !decoder.mNextStreamSourceID) {
           // We have completed draining the decoder following WaitingForData.
           // Set up the internal seek machinery to be able to resume from the
           // last sample decoded.
-          LOG("Seeking to last sample time: %lld",
+          LOG("Seeking to last sample time: %" PRId64,
               decoder.mLastSampleTime.ref().mStart.ToMicroseconds());
           InternalSeek(aTrack,
                        InternalSeekTarget(decoder.mLastSampleTime.ref(), true));
         }
         if (!decoder.mReceivedNewData) {
           LOG("Rejecting %s promise: WAITING_FOR_DATA", TrackTypeToStr(aTrack));
           decoder.RejectPromise(NS_ERROR_DOM_MEDIA_WAITING_FOR_DATA, __func__);
         }
@@ -2106,17 +2108,18 @@ MediaFormatReader::Update(TrackType aTra
     } else if (aTrack == TrackType::kAudioTrack) {
       decoder.Flush();
     }
     return;
   }
 
   bool needInput = NeedInput(decoder);
 
-  LOGV("Update(%s) ni=%d no=%d in:%llu out:%llu qs=%u decoding:%d flushing:%d "
+  LOGV("Update(%s) ni=%d no=%d in:%" PRIu64 " out:%" PRIu64
+       " qs=%u decoding:%d flushing:%d "
        "shutdown:%d pending:%u waiting:%d promise:%d sid:%u",
        TrackTypeToStr(aTrack), needInput, needOutput, decoder.mNumSamplesInput,
        decoder.mNumSamplesOutput, uint32_t(size_t(decoder.mSizeOfQueue)),
        decoder.mDecodeRequest.Exists(), decoder.mFlushRequest.Exists(),
        decoder.mShutdownRequest.Exists(), uint32_t(decoder.mOutput.Length()),
        decoder.mWaitingForData, decoder.HasPromise(),
        decoder.mLastStreamSourceID);
 
@@ -2149,17 +2152,17 @@ MediaFormatReader::Update(TrackType aTra
   HandleDemuxedSamples(aTrack, a);
 }
 
 void
 MediaFormatReader::ReturnOutput(MediaData* aData, TrackType aTrack)
 {
   MOZ_ASSERT(GetDecoderData(aTrack).HasPromise());
   MOZ_DIAGNOSTIC_ASSERT(aData->mType != MediaData::NULL_DATA);
-  LOG("Resolved data promise for %s [%lld, %lld]", TrackTypeToStr(aTrack),
+  LOG("Resolved data promise for %s [%" PRId64 ", %" PRId64 "]", TrackTypeToStr(aTrack),
       aData->mTime, aData->GetEndTime());
 
   if (aTrack == TrackInfo::kAudioTrack) {
     AudioData* audioData = static_cast<AudioData*>(aData);
 
     if (audioData->mChannels != mInfo.mAudio.mChannels
         || audioData->mRate != mInfo.mAudio.mRate) {
       LOG("change of audio format (rate:%d->%d). "
@@ -2295,17 +2298,17 @@ MediaFormatReader::DropDecodedSamples(Tr
     mDecoder->NotifyDecodedFrames({ 0, 0, lengthDecodedQueue });
   }
 }
 
 void
 MediaFormatReader::SkipVideoDemuxToNextKeyFrame(media::TimeUnit aTimeThreshold)
 {
   MOZ_ASSERT(OnTaskQueue());
-  LOG("Skipping up to %lld", aTimeThreshold.ToMicroseconds());
+  LOG("Skipping up to %" PRId64, aTimeThreshold.ToMicroseconds());
 
   // We've reached SkipVideoDemuxToNextKeyFrame when our decoding is late.
   // As such we can drop all already decoded samples and discard all pending
   // samples.
   DropDecodedSamples(TrackInfo::kVideoTrack);
 
   mVideo.mTrackDemuxer->SkipToNextRandomAccessPoint(aTimeThreshold)
     ->Then(OwnerThread(), __func__, this,
@@ -2380,17 +2383,17 @@ MediaFormatReader::OnVideoSkipFailed(
   }
 }
 
 RefPtr<MediaDecoderReader::SeekPromise>
 MediaFormatReader::Seek(const SeekTarget& aTarget)
 {
   MOZ_ASSERT(OnTaskQueue());
 
-  LOG("aTarget=(%lld)", aTarget.GetTime().ToMicroseconds());
+  LOG("aTarget=(%" PRId64 ")", aTarget.GetTime().ToMicroseconds());
 
   MOZ_DIAGNOSTIC_ASSERT(mSeekPromise.IsEmpty());
   MOZ_DIAGNOSTIC_ASSERT(!mVideo.HasPromise());
   MOZ_DIAGNOSTIC_ASSERT(aTarget.IsVideoOnly() || !mAudio.HasPromise());
   MOZ_DIAGNOSTIC_ASSERT(mPendingSeekTime.isNothing());
   MOZ_DIAGNOSTIC_ASSERT(mVideo.mTimeThreshold.isNothing());
   MOZ_DIAGNOSTIC_ASSERT(aTarget.IsVideoOnly()
                         || mAudio.mTimeThreshold.isNothing());
@@ -2465,17 +2468,17 @@ MediaFormatReader::AttemptSeek()
     MOZ_CRASH();
   }
 }
 
 void
 MediaFormatReader::OnSeekFailed(TrackType aTrack, const MediaResult& aError)
 {
   MOZ_ASSERT(OnTaskQueue());
-  LOGV("%s failure:%u", TrackTypeToStr(aTrack), aError.Code());
+  LOGV("%s failure:%" PRIu32, TrackTypeToStr(aTrack), static_cast<uint32_t>(aError.Code()));
   if (aTrack == TrackType::kVideoTrack) {
     mVideo.mSeekRequest.Complete();
   } else {
     mAudio.mSeekRequest.Complete();
   }
 
   if (aError == NS_ERROR_DOM_MEDIA_WAITING_FOR_DATA) {
     if (HasVideo()
@@ -2516,30 +2519,30 @@ MediaFormatReader::OnSeekFailed(TrackTyp
                                                : MediaData::VIDEO_DATA;
   mSeekPromise.Reject(SeekRejectValue(type, aError), __func__);
 }
 
 void
 MediaFormatReader::DoVideoSeek()
 {
   MOZ_ASSERT(mPendingSeekTime.isSome());
-  LOGV("Seeking video to %lld", mPendingSeekTime.ref().ToMicroseconds());
+  LOGV("Seeking video to %" PRId64, mPendingSeekTime.ref().ToMicroseconds());
   media::TimeUnit seekTime = mPendingSeekTime.ref();
   mVideo.mTrackDemuxer->Seek(seekTime)
     ->Then(OwnerThread(), __func__, this,
            &MediaFormatReader::OnVideoSeekCompleted,
            &MediaFormatReader::OnVideoSeekFailed)
     ->Track(mVideo.mSeekRequest);
 }
 
 void
 MediaFormatReader::OnVideoSeekCompleted(media::TimeUnit aTime)
 {
   MOZ_ASSERT(OnTaskQueue());
-  LOGV("Video seeked to %lld", aTime.ToMicroseconds());
+  LOGV("Video seeked to %" PRId64, aTime.ToMicroseconds());
   mVideo.mSeekRequest.Complete();
 
   mPreviousDecodedKeyframeTime_us = sNoPreviousDecodedKeyframe;
 
   SetVideoDecodeThreshold();
 
   if (HasAudio() && !mOriginalSeekTarget.IsVideoOnly()) {
     MOZ_ASSERT(mPendingSeekTime.isSome());
@@ -2591,38 +2594,38 @@ MediaFormatReader::SetVideoDecodeThresho
     if (!keyframe.IsValid() || keyframe.IsInfinite()) {
       return;
     }
     threshold = mOriginalSeekTarget.GetTime();
   } else {
     return;
   }
 
-  LOG("Set seek threshold to %lld", threshold.ToMicroseconds());
+  LOG("Set seek threshold to %" PRId64, threshold.ToMicroseconds());
   mVideo.mDecoder->SetSeekThreshold(threshold);
 }
 
 void
 MediaFormatReader::DoAudioSeek()
 {
   MOZ_ASSERT(mPendingSeekTime.isSome());
-  LOGV("Seeking audio to %lld", mPendingSeekTime.ref().ToMicroseconds());
+  LOGV("Seeking audio to %" PRId64, mPendingSeekTime.ref().ToMicroseconds());
   media::TimeUnit seekTime = mPendingSeekTime.ref();
   mAudio.mTrackDemuxer->Seek(seekTime)
     ->Then(OwnerThread(), __func__, this,
            &MediaFormatReader::OnAudioSeekCompleted,
            &MediaFormatReader::OnAudioSeekFailed)
     ->Track(mAudio.mSeekRequest);
 }
 
 void
 MediaFormatReader::OnAudioSeekCompleted(media::TimeUnit aTime)
 {
   MOZ_ASSERT(OnTaskQueue());
-  LOGV("Audio seeked to %lld", aTime.ToMicroseconds());
+  LOGV("Audio seeked to %" PRId64, aTime.ToMicroseconds());
   mAudio.mSeekRequest.Complete();
   mPendingSeekTime.reset();
   mSeekPromise.Resolve(aTime, __func__);
 }
 
 void
 MediaFormatReader::OnAudioSeekFailed(const MediaResult& aError)
 {
@@ -2778,42 +2781,42 @@ MediaFormatReader::GetMozDebugReaderData
     audioName = mAudio.mDescription;
   }
   if (HasVideo()) {
     MutexAutoLock mon(mVideo.mMutex);
     videoName = mVideo.mDescription;
   }
 
   result += nsPrintfCString("audio decoder: %s\n", audioName);
-  result += nsPrintfCString("audio frames decoded: %lld\n",
+  result += nsPrintfCString("audio frames decoded: %" PRIu64 "\n",
                             mAudio.mNumSamplesOutputTotal);
   if (HasAudio()) {
     result += nsPrintfCString(
-      "audio state: ni=%d no=%d demuxr:%d demuxq:%d tt:%f tths:%d in:%llu "
-      "out:%llu qs=%u pending:%u waiting:%d sid:%u\n",
+      "audio state: ni=%d no=%d demuxr:%d demuxq:%d tt:%f tths:%d in:%" PRIu64
+      " out:%" PRIu64 " qs=%u pending:%u waiting:%d sid:%u\n",
       NeedInput(mAudio), mAudio.HasPromise(), mAudio.mDemuxRequest.Exists(),
       int(mAudio.mQueuedSamples.Length()),
       mAudio.mTimeThreshold ? mAudio.mTimeThreshold.ref().Time().ToSeconds()
                             : -1.0,
       mAudio.mTimeThreshold ? mAudio.mTimeThreshold.ref().mHasSeeked : -1,
       mAudio.mNumSamplesInput, mAudio.mNumSamplesOutput,
       unsigned(size_t(mAudio.mSizeOfQueue)), unsigned(mAudio.mOutput.Length()),
       mAudio.mWaitingForData, mAudio.mLastStreamSourceID);
   }
   result += nsPrintfCString("video decoder: %s\n", videoName);
   result +=
     nsPrintfCString("hardware video decoding: %s\n",
                     VideoIsHardwareAccelerated() ? "enabled" : "disabled");
-  result += nsPrintfCString("video frames decoded: %lld (skipped:%lld)\n",
+  result += nsPrintfCString("video frames decoded: %" PRIu64 " (skipped:%" PRIu64 ")\n",
                             mVideo.mNumSamplesOutputTotal,
                             mVideo.mNumSamplesSkippedTotal);
   if (HasVideo()) {
     result += nsPrintfCString(
-      "video state: ni=%d no=%d demuxr:%d demuxq:%d tt:%f tths:%d in:%llu "
-      "out:%llu qs=%u pending:%u waiting:%d sid:%u\n",
+      "video state: ni=%d no=%d demuxr:%d demuxq:%d tt:%f tths:%d in:%" PRIu64
+      " out:%" PRIu64 " qs=%u pending:%u waiting:%d sid:%u\n",
       NeedInput(mVideo), mVideo.HasPromise(), mVideo.mDemuxRequest.Exists(),
       int(mVideo.mQueuedSamples.Length()),
       mVideo.mTimeThreshold ? mVideo.mTimeThreshold.ref().Time().ToSeconds()
                             : -1.0,
       mVideo.mTimeThreshold ? mVideo.mTimeThreshold.ref().mHasSeeked : -1,
       mVideo.mNumSamplesInput, mVideo.mNumSamplesOutput,
       unsigned(size_t(mVideo.mSizeOfQueue)), unsigned(mVideo.mOutput.Length()),
       mVideo.mWaitingForData, mVideo.mLastStreamSourceID);
--- a/dom/media/MediaManager.cpp
+++ b/dom/media/MediaManager.cpp
@@ -893,17 +893,17 @@ nsresult MediaDevice::Restart(const dom:
 
 nsresult MediaDevice::Deallocate() {
   return GetSource()->Deallocate(mAllocationHandle);
 }
 
 void
 MediaOperationTask::ReturnCallbackError(nsresult rv, const char* errorLog)
 {
-  MM_LOG(("%s , rv=%d", errorLog, rv));
+  MM_LOG(("%s , rv=%" PRIu32, errorLog, static_cast<uint32_t>(rv)));
   NS_DispatchToMainThread(do_AddRef(new ReleaseMediaOperationResource(mStream.forget(),
     mOnTracksAvailableCallback.forget())));
   nsString log;
 
   log.AssignASCII(errorLog);
   nsCOMPtr<nsIDOMGetUserMediaSuccessCallback> onSuccess;
   RefPtr<MediaMgrError> error = new MediaMgrError(
     NS_LITERAL_STRING("InternalError"), log);
@@ -1467,17 +1467,17 @@ public:
               NormalizedConstraints(constraints), videos, mIsChrome);
         }
         if (mAudioDevice) {
           mAudioDevice->Deallocate();
         }
       }
     }
     if (errorMsg) {
-      LOG(("%s %d", errorMsg, rv));
+      LOG(("%s %" PRIu32, errorMsg, static_cast<uint32_t>(rv)));
       if (badConstraint) {
         Fail(NS_LITERAL_STRING("OverconstrainedError"),
              NS_LITERAL_STRING(""),
              NS_ConvertUTF8toUTF16(badConstraint));
       } else {
         Fail(NS_LITERAL_STRING("NotReadableError"),
              NS_ConvertUTF8toUTF16(errorMsg));
       }
@@ -2667,17 +2667,17 @@ StopSharingCallback(MediaManager *aThis,
   }
 }
 
 
 void
 MediaManager::OnNavigation(uint64_t aWindowID)
 {
   MOZ_ASSERT(NS_IsMainThread());
-  LOG(("OnNavigation for %llu", aWindowID));
+  LOG(("OnNavigation for %" PRIu64, aWindowID));
 
   // Stop the streams for this window. The runnables check this value before
   // making a call to content.
 
   nsTArray<nsString>* callIDs;
   if (mCallIds.Get(aWindowID, &callIDs)) {
     for (auto& callID : *callIDs) {
       mActiveCallbacks.Remove(callID);
@@ -2735,36 +2735,36 @@ MediaManager::AddWindowID(uint64_t aWind
 void
 MediaManager::RemoveWindowID(uint64_t aWindowId)
 {
   mActiveWindows.Remove(aWindowId);
 
   // get outer windowID
   auto* window = nsGlobalWindow::GetInnerWindowWithId(aWindowId);
   if (!window) {
-    LOG(("No inner window for %llu", aWindowId));
+    LOG(("No inner window for %" PRIu64, aWindowId));
     return;
   }
 
   nsPIDOMWindowOuter* outer = window->AsInner()->GetOuterWindow();
   if (!outer) {
-    LOG(("No outer window for inner %llu", aWindowId));
+    LOG(("No outer window for inner %" PRIu64, aWindowId));
     return;
   }
 
   uint64_t outerID = outer->WindowID();
 
   // Notify the UI that this window no longer has gUM active
   char windowBuffer[32];
   SprintfLiteral(windowBuffer, "%" PRIu64, outerID);
   nsString data = NS_ConvertUTF8toUTF16(windowBuffer);
 
   nsCOMPtr<nsIObserverService> obs = services::GetObserverService();
   obs->NotifyObservers(nullptr, "recording-window-ended", data.get());
-  LOG(("Sent recording-window-ended for window %llu (outer %llu)",
+  LOG(("Sent recording-window-ended for window %" PRIu64 " (outer %" PRIu64 ")",
        aWindowId, outerID));
 }
 
 void
 MediaManager::RemoveFromWindowList(uint64_t aWindowID,
   GetUserMediaCallbackMediaStreamListener *aListener)
 {
   MOZ_ASSERT(NS_IsMainThread());
@@ -3121,24 +3121,24 @@ MediaManager::Observe(nsISupports* aSubj
   } else if (!strcmp(aTopic, "getUserMedia:revoke")) {
     nsresult rv;
     // may be windowid or screen:windowid
     nsDependentString data(aData);
     if (Substring(data, 0, strlen("screen:")).EqualsLiteral("screen:")) {
       uint64_t windowID = PromiseFlatString(Substring(data, strlen("screen:"))).ToInteger64(&rv);
       MOZ_ASSERT(NS_SUCCEEDED(rv));
       if (NS_SUCCEEDED(rv)) {
-        LOG(("Revoking Screen/windowCapture access for window %llu", windowID));
+        LOG(("Revoking Screen/windowCapture access for window %" PRIu64, windowID));
         StopScreensharing(windowID);
       }
     } else {
       uint64_t windowID = nsString(aData).ToInteger64(&rv);
       MOZ_ASSERT(NS_SUCCEEDED(rv));
       if (NS_SUCCEEDED(rv)) {
-        LOG(("Revoking MediaCapture access for window %llu", windowID));
+        LOG(("Revoking MediaCapture access for window %" PRIu64, windowID));
         OnNavigation(windowID);
       }
     }
     return NS_OK;
   }
 #ifdef MOZ_WIDGET_GONK
   else if (!strcmp(aTopic, "phone-state-changed")) {
     nsString state(aData);
@@ -3267,29 +3267,29 @@ MediaManager::MediaCaptureWindowState(ns
   *aAppShare = false;
   *aBrowserShare = false;
 
   nsCOMPtr<nsPIDOMWindowInner> piWin = do_QueryInterface(aWindow);
   if (piWin) {
     IterateWindowListeners(piWin, CaptureWindowStateCallback, &data);
   }
 #ifdef DEBUG
-  LOG(("%s: window %lld capturing %s %s %s %s %s %s", __FUNCTION__, piWin ? piWin->WindowID() : -1,
+  LOG(("%s: window %" PRIu64 " capturing %s %s %s %s %s %s", __FUNCTION__, piWin ? piWin->WindowID() : -1,
        *aVideo ? "video" : "", *aAudio ? "audio" : "",
        *aScreenShare ? "screenshare" : "",  *aWindowShare ? "windowshare" : "",
        *aAppShare ? "appshare" : "", *aBrowserShare ? "browsershare" : ""));
 #endif
   return NS_OK;
 }
 
 NS_IMETHODIMP
 MediaManager::SanitizeDeviceIds(int64_t aSinceWhen)
 {
   MOZ_ASSERT(NS_IsMainThread());
-  LOG(("%s: sinceWhen = %llu", __FUNCTION__, aSinceWhen));
+  LOG(("%s: sinceWhen = %" PRId64, __FUNCTION__, aSinceWhen));
 
   media::SanitizeOriginKeys(aSinceWhen, false); // we fire and forget
   return NS_OK;
 }
 
 static void
 StopScreensharingCallback(MediaManager *aThis,
                           uint64_t aWindowID,
--- a/dom/media/MediaPrefs.h
+++ b/dom/media/MediaPrefs.h
@@ -108,17 +108,16 @@ private:
   DECL_MEDIA_PREF("media.use-blank-decoder",                  PDMUseBlankDecoder, bool, false);
   DECL_MEDIA_PREF("media.gpu-process-decoder",                PDMUseGPUDecoder, bool, false);
 #ifdef MOZ_GONK_MEDIACODEC
   DECL_MEDIA_PREF("media.gonk.enabled",                       PDMGonkDecoderEnabled, bool, true);
 #endif
 #ifdef MOZ_WIDGET_ANDROID
   DECL_MEDIA_PREF("media.android-media-codec.enabled",        PDMAndroidMediaCodecEnabled, bool, false);
   DECL_MEDIA_PREF("media.android-media-codec.preferred",      PDMAndroidMediaCodecPreferred, bool, false);
-  DECL_MEDIA_PREF("media.android-remote-codec.enabled",       PDMAndroidRemoteCodecEnabled, bool, false);
 #endif
 #ifdef MOZ_FFMPEG
   DECL_MEDIA_PREF("media.ffmpeg.enabled",                     PDMFFmpegEnabled, bool, true);
   DECL_MEDIA_PREF("media.libavcodec.allow-obsolete",          LibavcodecAllowObsolete, bool, false);
 #endif
 #ifdef MOZ_FFVPX
   DECL_MEDIA_PREF("media.ffvpx.enabled",                      PDMFFVPXEnabled, bool, true);
 #endif
--- a/dom/media/MediaResource.cpp
+++ b/dom/media/MediaResource.cpp
@@ -353,17 +353,17 @@ ChannelMediaResource::ParseContentRangeH
   if (aRangeTotalText[0] == '*') {
     aRangeTotal = -1;
   } else {
     aRangeTotal = aRangeTotalText.ToInteger64(&rv);
     NS_ENSURE_TRUE(aRangeEnd < aRangeTotal, NS_ERROR_ILLEGAL_VALUE);
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
-  CMLOG("Received bytes [%lld] to [%lld] of [%lld] for decoder[%p]",
+  CMLOG("Received bytes [%" PRId64 "] to [%" PRId64 "] of [%" PRId64 "] for decoder[%p]",
         aRangeStart, aRangeEnd, aRangeTotal, mCallback.get());
 
   return NS_OK;
 }
 
 nsresult
 ChannelMediaResource::OnStopRequest(nsIRequest* aRequest, nsresult aStatus)
 {
@@ -435,17 +435,17 @@ ChannelMediaResource::CopySegmentToCache
                                          uint32_t aCount,
                                          uint32_t *aWriteCount)
 {
   CopySegmentClosure* closure = static_cast<CopySegmentClosure*>(aClosure);
 
   closure->mResource->mCallback->NotifyDataArrived();
 
   // Keep track of where we're up to.
-  RESOURCE_LOG("%p [ChannelMediaResource]: CopySegmentToCache at mOffset [%lld] add "
+  RESOURCE_LOG("%p [ChannelMediaResource]: CopySegmentToCache at mOffset [%" PRId64 "] add "
                "[%d] bytes for decoder[%p]",
                closure->mResource, closure->mResource->mOffset, aCount,
                closure->mResource->mCallback.get());
   closure->mResource->mOffset += aCount;
 
   closure->mResource->mCacheStream.NotifyDataReceived(aCount, aFromSegment,
                                                       closure->mPrincipal);
   *aWriteCount = aCount;
@@ -891,17 +891,17 @@ ChannelMediaResource::CacheClientNotifyS
   mCallback->NotifySuspendedStatusChanged();
 }
 
 nsresult
 ChannelMediaResource::CacheClientSeek(int64_t aOffset, bool aResume)
 {
   NS_ASSERTION(NS_IsMainThread(), "Don't call on non-main thread");
 
-  CMLOG("CacheClientSeek requested for aOffset [%lld] for decoder [%p]",
+  CMLOG("CacheClientSeek requested for aOffset [%" PRId64 "] for decoder [%p]",
         aOffset, mCallback.get());
 
   CloseChannel();
 
   mOffset = aOffset;
 
   // Don't report close of the channel because the channel is not closed for
   // download ended, but for internal changes in the read position.
--- a/dom/media/MediaResult.h
+++ b/dom/media/MediaResult.h
@@ -46,20 +46,20 @@ public:
   bool operator!=(nsresult aResult) const { return aResult != mCode; }
   operator nsresult () const { return mCode; }
 
   nsCString Description() const
   {
     if (NS_SUCCEEDED(mCode)) {
       return nsCString();
     }
-    return nsPrintfCString("0x%08x: %s", mCode, mMessage.get());
+    return nsPrintfCString("0x%08" PRIx32 ": %s", static_cast<uint32_t>(mCode), mMessage.get());
   }
 
 private:
   nsresult mCode;
   nsCString mMessage;
 };
 
 #define RESULT_DETAIL(arg, ...) nsPrintfCString("%s: " arg, __func__, ##__VA_ARGS__)
 
 } // namespace mozilla
-#endif // MediaResult_h_
\ No newline at end of file
+#endif // MediaResult_h_
--- a/dom/media/MediaStreamGraph.cpp
+++ b/dom/media/MediaStreamGraph.cpp
@@ -1,15 +1,16 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-*/
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "MediaStreamGraphImpl.h"
 #include "mozilla/MathAlgorithms.h"
+#include "mozilla/SizePrintfMacros.h"
 #include "mozilla/Unused.h"
 
 #include "AudioSegment.h"
 #include "VideoSegment.h"
 #include "nsContentUtils.h"
 #include "nsIObserver.h"
 #include "nsPrintfCString.h"
 #include "nsServiceManagerUtils.h"
@@ -111,25 +112,25 @@ MediaStreamGraphImpl::AddStreamGraphThre
   if (aStream->IsSuspended()) {
     mSuspendedStreams.AppendElement(aStream);
     LOG(LogLevel::Debug,
         ("Adding media stream %p to the graph, in the suspended stream array",
          aStream));
   } else {
     mStreams.AppendElement(aStream);
     LOG(LogLevel::Debug,
-        ("Adding media stream %p to graph %p, count %lu",
+        ("Adding media stream %p to graph %p, count %" PRIuSIZE,
          aStream,
          this,
          mStreams.Length()));
     LOG(LogLevel::Debug,
-        ("Adding media stream %p to graph %p, count %lu",
+        ("Adding media stream %p to graph %p, count %" PRIuSIZE,
          aStream,
          this,
-         (long)mStreams.Length()));
+         mStreams.Length()));
   }
 
   SetStreamOrderDirty();
 }
 
 void
 MediaStreamGraphImpl::RemoveStreamGraphThread(MediaStream* aStream)
 {
@@ -150,25 +151,25 @@ MediaStreamGraphImpl::RemoveStreamGraphT
 
   if (aStream->IsSuspended()) {
     mSuspendedStreams.RemoveElement(aStream);
   } else {
     mStreams.RemoveElement(aStream);
   }
 
   LOG(LogLevel::Debug,
-      ("Removed media stream %p from graph %p, count %lu",
+      ("Removed media stream %p from graph %p, count %" PRIuSIZE,
        aStream,
        this,
        mStreams.Length()));
   LOG(LogLevel::Debug,
-      ("Removed media stream %p from graph %p, count %lu",
+      ("Removed media stream %p from graph %p, count %" PRIuSIZE,
        aStream,
        this,
-       (long)mStreams.Length()));
+       mStreams.Length()));
 
   NS_RELEASE(aStream); // probably destroying it
 }
 
 void
 MediaStreamGraphImpl::ExtractPendingInput(SourceMediaStream* aStream,
                                           GraphTime aDesiredUpToTime,
                                           bool* aEnsureNextIteration)
@@ -264,34 +265,35 @@ MediaStreamGraphImpl::ExtractPendingInpu
         b.mListener->NotifyQueuedChanges(this, offset, *data->mData);
         if (data->mCommands & SourceMediaStream::TRACK_END) {
           b.mListener->NotifyEnded();
         }
       }
       if (data->mCommands & SourceMediaStream::TRACK_CREATE) {
         MediaSegment* segment = data->mData.forget();
         LOG(LogLevel::Debug,
-            ("SourceMediaStream %p creating track %d, start %lld, initial end "
-             "%lld",
+            ("SourceMediaStream %p creating track %d, start %" PRId64
+             ", initial end %" PRId64,
              aStream,
              data->mID,
              int64_t(data->mStart),
              int64_t(segment->GetDuration())));
 
         data->mEndOfFlushedData += segment->GetDuration();
         aStream->mTracks.AddTrack(data->mID, data->mStart, segment);
         // The track has taken ownership of data->mData, so let's replace
         // data->mData with an empty clone.
         data->mData = segment->CreateEmptyClone();
         data->mCommands &= ~SourceMediaStream::TRACK_CREATE;
         shouldNotifyTrackCreated = true;
       } else if (data->mData->GetDuration() > 0) {
         MediaSegment* dest = aStream->mTracks.FindTrack(data->mID)->GetSegment();
         LOG(LogLevel::Verbose,
-            ("SourceMediaStream %p track %d, advancing end from %lld to %lld",
+            ("SourceMediaStream %p track %d, advancing end from %" PRId64
+             " to %" PRId64,
              aStream,
              data->mID,
              int64_t(dest->GetDuration()),
              int64_t(dest->GetDuration() + data->mData->GetDuration())));
         data->mEndOfFlushedData += data->mData->GetDuration();
         dest->AppendFrom(data->mData);
       }
       if (data->mCommands & SourceMediaStream::TRACK_END) {
@@ -471,17 +473,18 @@ MediaStreamGraphImpl::WillUnderrun(Media
   // This stream isn't finished or suspended. We don't need to call
   // StreamTimeToGraphTime since an underrun is the only thing that can block
   // it.
   GraphTime bufferEnd = aStream->GetTracksEnd() + aStream->mTracksStartTime;
 #ifdef DEBUG
   if (bufferEnd < mProcessedTime) {
     LOG(LogLevel::Error,
         ("MediaStream %p underrun, "
-         "bufferEnd %f < mProcessedTime %f (%lld < %lld), Streamtime %lld",
+         "bufferEnd %f < mProcessedTime %f (%" PRId64 " < %" PRId64
+         "), Streamtime %" PRId64,
          aStream,
          MediaTimeToSeconds(bufferEnd),
          MediaTimeToSeconds(mProcessedTime),
          bufferEnd,
          mProcessedTime,
          aStream->GetTracksEnd()));
     aStream->DumpTrackInfo();
     NS_ASSERTION(bufferEnd >= mProcessedTime, "Buffer underran");
@@ -896,32 +899,32 @@ MediaStreamGraphImpl::PlayAudio(MediaStr
       // Check how many ticks of sound we can provide if we are blocked some
       // time in the middle of this cycle.
       StreamTime toWrite = end - t;
 
       if (blocked) {
         output.InsertNullDataAtStart(toWrite);
         ticksWritten += toWrite;
         LOG(LogLevel::Verbose,
-            ("MediaStream %p writing %ld blocking-silence samples for "
-             "%f to %f (%ld to %ld)",
+            ("MediaStream %p writing %" PRId64 " blocking-silence samples for "
+             "%f to %f (%" PRId64 " to %" PRId64 ")",
              aStream,
              toWrite,
              MediaTimeToSeconds(t),
              MediaTimeToSeconds(end),
              offset,
              offset + toWrite));
       } else {
         StreamTime endTicksNeeded = offset + toWrite;
         StreamTime endTicksAvailable = audio->GetDuration();
 
         if (endTicksNeeded <= endTicksAvailable) {
           LOG(LogLevel::Verbose,
-              ("MediaStream %p writing %ld samples for %f to %f "
-               "(samples %ld to %ld)",
+              ("MediaStream %p writing %" PRId64 " samples for %f to %f "
+               "(samples %" PRId64 " to %" PRId64 ")",
                aStream,
                toWrite,
                MediaTimeToSeconds(t),
                MediaTimeToSeconds(end),
                offset,
                endTicksNeeded));
           output.AppendSlice(*audio, offset, endTicksNeeded);
           ticksWritten += toWrite;
@@ -929,33 +932,33 @@ MediaStreamGraphImpl::PlayAudio(MediaStr
         } else {
           // MOZ_ASSERT(track->IsEnded(), "Not enough data, and track not ended.");
           // If we are at the end of the track, maybe write the remaining
           // samples, and pad with/output silence.
           if (endTicksNeeded > endTicksAvailable &&
               offset < endTicksAvailable) {
             output.AppendSlice(*audio, offset, endTicksAvailable);
             LOG(LogLevel::Verbose,
-                ("MediaStream %p writing %ld samples for %f to %f "
-                 "(samples %ld to %ld)",
+                ("MediaStream %p writing %" PRId64 " samples for %f to %f "
+                 "(samples %" PRId64 " to %" PRId64 ")",
                  aStream,
                  toWrite,
                  MediaTimeToSeconds(t),
                  MediaTimeToSeconds(end),
                  offset,
                  endTicksNeeded));
             uint32_t available = endTicksAvailable - offset;
             ticksWritten += available;
             toWrite -= available;
             offset = endTicksAvailable;
           }
           output.AppendNullData(toWrite);
           LOG(LogLevel::Verbose,
-              ("MediaStream %p writing %ld padding slsamples for %f to "
-               "%f (samples %ld to %ld)",
+              ("MediaStream %p writing %" PRId64 " padding slsamples for %f to "
+               "%f (samples %" PRId64 " to %" PRId64 ")",
                aStream,
                toWrite,
                MediaTimeToSeconds(t),
                MediaTimeToSeconds(end),
                offset,
                endTicksNeeded));
           ticksWritten += toWrite;
         }
@@ -3849,17 +3852,17 @@ MediaStreamGraphImpl::SuspendOrResumeStr
     if (aAudioContextOperation == AudioContextOperation::Resume) {
       DecrementSuspendCount(stream);
     } else {
       IncrementSuspendCount(stream);
     }
   }
   LOG(LogLevel::Debug,
       ("Moving streams between suspended and running"
-       "state: mStreams: %d, mSuspendedStreams: %d",
+       "state: mStreams: %" PRIuSIZE ", mSuspendedStreams: %" PRIuSIZE,
        mStreams.Length(),
        mSuspendedStreams.Length()));
 #ifdef DEBUG
   // The intersection of the two arrays should be null.
   for (uint32_t i = 0; i < mStreams.Length(); i++) {
     for (uint32_t j = 0; j < mSuspendedStreams.Length(); j++) {
       MOZ_ASSERT(
         mStreams[i] != mSuspendedStreams[j],
--- a/dom/media/MediaTimer.cpp
+++ b/dom/media/MediaTimer.cpp
@@ -75,17 +75,17 @@ MediaTimer::OnMediaTimerThread()
   mThread->IsOnCurrentThread(&rv);
   return rv;
 }
 
 RefPtr<MediaTimerPromise>
 MediaTimer::WaitUntil(const TimeStamp& aTimeStamp, const char* aCallSite)
 {
   MonitorAutoLock mon(mMonitor);
-  TIMER_LOG("MediaTimer::WaitUntil %lld", RelativeMicroseconds(aTimeStamp));
+  TIMER_LOG("MediaTimer::WaitUntil %" PRId64, RelativeMicroseconds(aTimeStamp));
   Entry e(aTimeStamp, aCallSite);
   RefPtr<MediaTimerPromise> p = e.mPromise.get();
   mEntries.push(e);
   ScheduleUpdate();
   return p;
 }
 
 void
--- a/dom/media/MediaTimer.h
+++ b/dom/media/MediaTimer.h
@@ -2,32 +2,33 @@
 /* vim:set ts=2 sw=2 sts=2 et cindent: */
 /* 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/. */
 
 #if !defined(MediaTimer_h_)
 #define MediaTimer_h_
 
+#include "mozilla/IntegerPrintfMacros.h"
 #include "mozilla/Monitor.h"
 #include "mozilla/MozPromise.h"
 #include "mozilla/TimeStamp.h"
 
 #include <queue>
 
 #include "nsITimer.h"
 #include "mozilla/RefPtr.h"
 
 namespace mozilla {
 
 extern LazyLogModule gMediaTimerLog;
 
 #define TIMER_LOG(x, ...) \
   MOZ_ASSERT(gMediaTimerLog); \
-  MOZ_LOG(gMediaTimerLog, LogLevel::Debug, ("[MediaTimer=%p relative_t=%lld]" x, this, \
+  MOZ_LOG(gMediaTimerLog, LogLevel::Debug, ("[MediaTimer=%p relative_t=%" PRId64 "]" x, this, \
                                         RelativeMicroseconds(TimeStamp::Now()), ##__VA_ARGS__))
 
 // This promise type is only exclusive because so far there isn't a reason for
 // it not to be. Feel free to change that.
 typedef MozPromise<bool, bool, /* IsExclusive = */ true> MediaTimerPromise;
 
 // Timers only know how to fire at a given thread, which creates an impedence
 // mismatch with code that operates with TaskQueues. This class solves
--- a/dom/media/StreamTracks.cpp
+++ b/dom/media/StreamTracks.cpp
@@ -11,23 +11,23 @@ namespace mozilla {
 
 extern LazyLogModule gMediaStreamGraphLog;
 #define STREAM_LOG(type, msg) MOZ_LOG(gMediaStreamGraphLog, type, msg)
 
 #ifdef DEBUG
 void
 StreamTracks::DumpTrackInfo() const
 {
-  STREAM_LOG(LogLevel::Info, ("DumpTracks: mTracksKnownTime %lld", mTracksKnownTime));
+  STREAM_LOG(LogLevel::Info, ("DumpTracks: mTracksKnownTime %" PRId64, mTracksKnownTime));
   for (uint32_t i = 0; i < mTracks.Length(); ++i) {
     Track* track = mTracks[i];
     if (track->IsEnded()) {
       STREAM_LOG(LogLevel::Info, ("Track[%d] %d: ended", i, track->GetID()));
     } else {
-      STREAM_LOG(LogLevel::Info, ("Track[%d] %d: %lld", i, track->GetID(),
+      STREAM_LOG(LogLevel::Info, ("Track[%d] %d: %" PRId64 "", i, track->GetID(),
                                  track->GetEnd()));
     }
   }
 }
 #endif
 
 StreamTime
 StreamTracks::GetEnd() const
--- a/dom/media/eme/DetailedPromise.cpp
+++ b/dom/media/eme/DetailedPromise.cpp
@@ -37,19 +37,19 @@ DetailedPromise::~DetailedPromise()
   // unlinked, so don't have a reference to our actual JS Promise object
   // anymore.
   MaybeReportTelemetry(Failed);
 }
 
 void
 DetailedPromise::MaybeReject(nsresult aArg, const nsACString& aReason)
 {
-  nsPrintfCString msg("%s promise rejected 0x%x '%s'", mName.get(), aArg,
-                      PromiseFlatCString(aReason).get());
-  EME_LOG(msg.get());
+  nsPrintfCString msg("%s promise rejected 0x%" PRIx32 " '%s'", mName.get(),
+                      static_cast<uint32_t>(aArg), PromiseFlatCString(aReason).get());
+  EME_LOG("%s", msg.get());
 
   MaybeReportTelemetry(Failed);
 
   LogToBrowserConsole(NS_ConvertUTF8toUTF16(msg));
 
   ErrorResult rv;
   rv.ThrowDOMException(aArg, aReason);
   Promise::MaybeReject(rv);
--- a/dom/media/eme/MediaKeySession.cpp
+++ b/dom/media/eme/MediaKeySession.cpp
@@ -150,17 +150,18 @@ MediaKeySession::UpdateKeyStatusMap()
       nsPrintfCString("MediaKeySession[%p,'%s'] key statuses change {",
                       this, NS_ConvertUTF16toUTF8(mSessionId).get()));
     using IntegerType = typename std::underlying_type<MediaKeyStatus>::type;
     for (const CDMCaps::KeyStatus& status : keyStatuses) {
       message.Append(nsPrintfCString(" (%s,%s)", ToHexString(status.mId).get(),
         MediaKeyStatusValues::strings[static_cast<IntegerType>(status.mStatus)].value));
     }
     message.Append(" }");
-    EME_LOG(message.get());
+    // Use %s so we aren't exposing random strings to printf interpolation.
+    EME_LOG("%s", message.get());
   }
 }
 
 MediaKeyStatusMap*
 MediaKeySession::KeyStatuses() const
 {
   return mKeyStatusMap;
 }
--- a/dom/media/eme/MediaKeys.cpp
+++ b/dom/media/eme/MediaKeys.cpp
@@ -216,17 +216,18 @@ MediaKeys::RetrievePromise(PromiseId aId
   Release();
   return promise.forget();
 }
 
 void
 MediaKeys::RejectPromise(PromiseId aId, nsresult aExceptionCode,
                          const nsCString& aReason)
 {
-  EME_LOG("MediaKeys[%p]::RejectPromise(%d, 0x%x)", this, aId, aExceptionCode);
+  EME_LOG("MediaKeys[%p]::RejectPromise(%d, 0x%" PRIx32 ")",
+          this, aId, static_cast<uint32_t>(aExceptionCode));
 
   RefPtr<DetailedPromise> promise(RetrievePromise(aId));
   if (!promise) {
     return;
   }
 
   // This promise could be a createSession or loadSession promise,
   // so we might have a pending session waiting to be resolved into
@@ -477,17 +478,17 @@ IsSessionTypeSupported(const MediaKeySes
 }
 
 already_AddRefed<MediaKeySession>
 MediaKeys::CreateSession(JSContext* aCx,
                          MediaKeySessionType aSessionType,
                          ErrorResult& aRv)
 {
   if (!IsSessionTypeSupported(aSessionType, mConfig)) {
-    EME_LOG("MediaKeys[%p,'%s'] CreateSession() failed, unsupported session type", this);
+    EME_LOG("MediaKeys[%p] CreateSession() failed, unsupported session type", this);
     aRv.Throw(NS_ERROR_DOM_NOT_SUPPORTED_ERR);
     return nullptr;
   }
 
   if (!mProxy) {
     NS_WARNING("Tried to use a MediaKeys which lost its CDM");
     aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
     return nullptr;
--- a/dom/media/eme/mediadrm/MediaDrmCDMProxy.cpp
+++ b/dom/media/eme/mediadrm/MediaDrmCDMProxy.cpp
@@ -48,17 +48,18 @@ MediaDrmCDMProxy::Init(PromiseId aPromis
                        const nsAString& aTopLevelOrigin,
                        const nsAString& aName)
 {
   MOZ_ASSERT(NS_IsMainThread());
   NS_ENSURE_TRUE_VOID(!mKeys.IsNull());
 
   EME_LOG("MediaDrmCDMProxy::Init (%s, %s) %s",
           NS_ConvertUTF16toUTF8(aOrigin).get(),
-          NS_ConvertUTF16toUTF8(aTopLevelOrigin).get());
+          NS_ConvertUTF16toUTF8(aTopLevelOrigin).get(),
+          NS_ConvertUTF16toUTF8(aName).get());
 
   // Create a thread to work with cdm.
   if (!mOwnerThread) {
     nsresult rv = NS_NewNamedThread("MDCDMThread", getter_AddRefs(mOwnerThread));
     if (NS_FAILED(rv)) {
       RejectPromise(aPromiseId, NS_ERROR_DOM_INVALID_STATE_ERR,
                     NS_LITERAL_CSTRING("Couldn't create CDM thread MediaDrmCDMProxy::Init"));
       return;
--- a/dom/media/eme/mediadrm/MediaDrmProxySupport.cpp
+++ b/dom/media/eme/mediadrm/MediaDrmProxySupport.cpp
@@ -195,20 +195,17 @@ MediaDrmJavaCallbacksSupport::OnRejectPr
                                          reason);
 }
 
 MediaDrmProxySupport::MediaDrmProxySupport(const nsAString& aKeySystem)
   : mKeySystem(aKeySystem), mDestroyed(false)
 {
   mJavaCallbacks = MediaDrmProxy::NativeMediaDrmProxyCallbacks::New();
 
-  mBridgeProxy =
-    MediaDrmProxy::Create(mKeySystem,
-                          mJavaCallbacks,
-                          MediaPrefs::PDMAndroidRemoteCodecEnabled());
+  mBridgeProxy = MediaDrmProxy::Create(mKeySystem, mJavaCallbacks);
 
   MOZ_ASSERT(mBridgeProxy, "mBridgeProxy should not be null");
   mMediaDrmStubId = mBridgeProxy->GetStubId()->ToString();
 }
 
 MediaDrmProxySupport::~MediaDrmProxySupport()
 {
   MOZ_ASSERT(mDestroyed, "Shutdown() should be called before !!");
--- a/dom/media/encoder/MediaEncoder.cpp
+++ b/dom/media/encoder/MediaEncoder.cpp
@@ -186,17 +186,17 @@ MediaEncoder::CreateEncoder(const nsAStr
     mimeType = NS_LITERAL_STRING(AUDIO_OGG);
   }
   else {
     LOG(LogLevel::Error, ("Can not find any encoder to record this media stream"));
     return nullptr;
   }
   LOG(LogLevel::Debug, ("Create encoder result:a[%d] v[%d] w[%d] mimeType = %s.",
                       audioEncoder != nullptr, videoEncoder != nullptr,
-                      writer != nullptr, mimeType.get()));
+                      writer != nullptr, NS_ConvertUTF16toUTF8(mimeType).get()));
   if (videoEncoder && aVideoBitrate != 0) {
     videoEncoder->SetBitrate(aVideoBitrate);
   }
   if (audioEncoder && aAudioBitrate != 0) {
     audioEncoder->SetBitrate(aAudioBitrate);
   }
   encoder = new MediaEncoder(writer.forget(), audioEncoder.forget(),
                              videoEncoder.forget(), mimeType, aAudioBitrate,
--- a/dom/media/encoder/TrackEncoder.cpp
+++ b/dom/media/encoder/TrackEncoder.cpp
@@ -300,17 +300,17 @@ VideoTrackEncoder::AppendVideoSegment(co
       // This is the first real chunk in the track. Use its timestamp as the
       // starting point for this track.
       MOZ_ASSERT(!chunk.mTimeStamp.IsNull());
       const StreamTime nullDuration = mLastChunk.mDuration;
       mLastChunk = chunk;
       chunk.mDuration = 0;
 
       TRACK_LOG(LogLevel::Verbose,
-                ("[VideoTrackEncoder]: Got first video chunk after %lld ticks.",
+                ("[VideoTrackEncoder]: Got first video chunk after %" PRId64 " ticks.",
                  nullDuration));
       // Adapt to the time before the first frame. This extends the first frame
       // from [start, end] to [0, end], but it'll do for now.
       CheckedInt64 diff = FramesToUsecs(nullDuration, mTrackRate);
       if (!diff.isValid()) {
         NS_ERROR("null duration overflow");
         return NS_ERROR_DOM_MEDIA_OVERFLOW_ERR;
       }
@@ -324,24 +324,24 @@ VideoTrackEncoder::AppendVideoSegment(co
       TRACK_LOG(LogLevel::Verbose,
                 ("[VideoTrackEncoder]: Got dupe or null chunk."));
       // This is the same frame as before (or null). We extend the last chunk
       // with its duration.
       mLastChunk.mDuration += chunk.mDuration;
 
       if (mLastChunk.mDuration < mTrackRate) {
         TRACK_LOG(LogLevel::Verbose,
-                  ("[VideoTrackEncoder]: Ignoring dupe/null chunk of duration "
-                   "%lld", chunk.mDuration));
+                  ("[VideoTrackEncoder]: Ignoring dupe/null chunk of duration %" PRId64,
+                   chunk.mDuration));
         continue;
       }
 
       TRACK_LOG(LogLevel::Verbose,
-                ("[VideoTrackEncoder]: Chunk >1 second. duration=%lld, "
-                 "trackRate=%lld", mLastChunk.mDuration, mTrackRate));
+                ("[VideoTrackEncoder]: Chunk >1 second. duration=%" PRId64 ", "
+                 "trackRate=%" PRId32, mLastChunk.mDuration, mTrackRate));
 
       // If we have gotten dupes for over a second, we force send one
       // to the encoder to make sure there is some output.
       chunk.mTimeStamp = mLastChunk.mTimeStamp + TimeDuration::FromSeconds(1);
 
       // chunk's duration has already been accounted for.
       chunk.mDuration = 0;
 
@@ -377,17 +377,17 @@ VideoTrackEncoder::AppendVideoSegment(co
     if (duration.isValid()) {
       if (duration.value() <= 0) {
         // The timestamp for mLastChunk is newer than for chunk.
         // This means the durations reported from MediaStreamGraph for
         // mLastChunk were larger than the timestamp diff - and durations were
         // used to trigger the 1-second frame above. This could happen due to
         // drift or underruns in the graph.
         TRACK_LOG(LogLevel::Warning,
-                  ("[VideoTrackEncoder]: Underrun detected. Diff=%lld",
+                  ("[VideoTrackEncoder]: Underrun detected. Diff=%" PRId64,
                    duration.value()));
         chunk.mTimeStamp = mLastChunk.mTimeStamp;
       } else {
         mEncodedTicks += duration.value();
         mRawSegment.AppendFrame(lastImage.forget(),
                                 duration.value(),
                                 mLastChunk.mFrame.GetIntrinsicSize(),
                                 PRINCIPAL_HANDLE_NONE,
--- a/dom/media/encoder/VP8TrackEncoder.cpp
+++ b/dom/media/encoder/VP8TrackEncoder.cpp
@@ -246,17 +246,17 @@ VP8TrackEncoder::GetEncodedPartitions(En
       NS_ERROR("Duration overflow");
       return NS_ERROR_DOM_MEDIA_OVERFLOW_ERR;
     }
 
     mExtractedDurationUs = totalDuration;
     videoData->SetDuration((uint64_t)duration.value());
     videoData->SwapInFrameData(frameData);
     VP8LOG(LogLevel::Verbose,
-           "GetEncodedPartitions TimeStamp %lld, Duration %lld, FrameType %d",
+           "GetEncodedPartitions TimeStamp %" PRIu64 ", Duration %" PRIu64 ", FrameType %d",
            videoData->GetTimeStamp(), videoData->GetDuration(),
            videoData->GetFrameType());
     aData.AppendEncodedFrame(videoData);
   }
 
   return pkt ? NS_OK : NS_ERROR_NOT_AVAILABLE;
 }
 
@@ -545,17 +545,17 @@ VP8TrackEncoder::GetEncodedTrack(Encoded
 
   StreamTime totalProcessedDuration = 0;
   TimeStamp timebase = TimeStamp::Now();
   EncodeOperation nextEncodeOperation = ENCODE_NORMAL_FRAME;
 
   for (VideoSegment::ChunkIterator iter(mSourceSegment);
        !iter.IsEnded(); iter.Next()) {
     VideoChunk &chunk = *iter;
-    VP8LOG(LogLevel::Verbose, "nextEncodeOperation is %d for frame of duration %lld",
+    VP8LOG(LogLevel::Verbose, "nextEncodeOperation is %d for frame of duration %" PRId64,
              nextEncodeOperation, chunk.GetDuration());
 
     // Encode frame.
     if (nextEncodeOperation != SKIP_FRAME) {
       nsresult rv = PrepareRawFrame(chunk);
       NS_ENSURE_SUCCESS(rv, NS_ERROR_FAILURE);
 
       // Encode the data with VP8 encoder
--- a/dom/media/flac/FlacDemuxer.cpp
+++ b/dom/media/flac/FlacDemuxer.cpp
@@ -2,16 +2,17 @@
 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "FlacDemuxer.h"
 
 #include "mozilla/Maybe.h"
+#include "mozilla/SizePrintfMacros.h"
 #include "mp4_demuxer/BitReader.h"
 #include "nsAutoPtr.h"
 #include "prenv.h"
 #include "FlacFrameParser.h"
 #include "VideoUtils.h"
 #include "TimeUnits.h"
 
 #ifdef PR_LOGGING
@@ -733,17 +734,17 @@ FlacTrackDemuxer::Seek(const TimeUnit& a
   const TimeUnit seekTime = ScanUntil(aTime);
 
   return SeekPromise::CreateAndResolve(seekTime, __func__);
 }
 
 TimeUnit
 FlacTrackDemuxer::FastSeek(const TimeUnit& aTime)
 {
-  LOG("FastSeek(%f) avgFrameLen=%f mParsedFramesDuration=%f offset=%lld",
+  LOG("FastSeek(%f) avgFrameLen=%f mParsedFramesDuration=%f offset=%" PRId64,
       aTime.ToSeconds(), AverageFrameLength(),
       mParsedFramesDuration.ToSeconds(), GetResourceOffset());
 
   // Invalidate current frames in the parser.
   mParser->EndFrameSession();
 
   if (!mParser->FirstFrame().IsValid()) {
     // Something wrong, and there's nothing to seek to anyway, so we can
@@ -780,17 +781,17 @@ FlacTrackDemuxer::FastSeek(const TimeUni
     mSource.Seek(SEEK_SET, pivot);
     flac::Frame frame;
     if (!frame.FindNext(mSource)) {
       NS_WARNING("We should have found a point");
       break;
     }
     timeSeekedTo = frame.Time();
 
-    LOGV("FastSeek: interation:%u found:%f @ %lld",
+    LOGV("FastSeek: interation:%u found:%f @ %" PRId64,
          iterations, timeSeekedTo.ToSeconds(), frame.Offset());
 
     if (lastFoundOffset && lastFoundOffset.ref() == frame.Offset()) {
       // Same frame found twice. We're done.
       break;
     }
     lastFoundOffset = Some(frame.Offset());
 
@@ -817,17 +818,17 @@ FlacTrackDemuxer::FastSeek(const TimeUni
   }
 
   return timeSeekedTo;
 }
 
 TimeUnit
 FlacTrackDemuxer::ScanUntil(const TimeUnit& aTime)
 {
-  LOG("ScanUntil(%f avgFrameLen=%f mParsedFramesDuration=%f offset=%lld",
+  LOG("ScanUntil(%f avgFrameLen=%f mParsedFramesDuration=%f offset=%" PRId64,
       aTime.ToSeconds(), AverageFrameLength(),
       mParsedFramesDuration.ToSeconds(), mParser->CurrentFrame().Offset());
 
    if (!mParser->FirstFrame().IsValid()
        || aTime <= mParser->FirstFrame().Time()) {
      return FastSeek(aTime);
    }
 
@@ -847,18 +848,18 @@ FlacTrackDemuxer::ScanUntil(const TimeUn
   mParser->EndFrameSession();
   mSource.Seek(SEEK_SET, previousOffset);
   return previousTime;
 }
 
 RefPtr<FlacTrackDemuxer::SamplesPromise>
 FlacTrackDemuxer::GetSamples(int32_t aNumSamples)
 {
-  LOGV("GetSamples(%d) Begin offset=%lld mParsedFramesDuration=%f"
-       " mTotalFrameLen=%llu",
+  LOGV("GetSamples(%d) Begin offset=%" PRId64 " mParsedFramesDuration=%f"
+       " mTotalFrameLen=%" PRIu64,
        aNumSamples, GetResourceOffset(), mParsedFramesDuration.ToSeconds(),
        mTotalFrameLen);
 
   if (!aNumSamples) {
     return SamplesPromise::CreateAndReject(
       NS_ERROR_DOM_MEDIA_DEMUXER_ERR, __func__);
   }
 
@@ -867,18 +868,18 @@ FlacTrackDemuxer::GetSamples(int32_t aNu
   while (aNumSamples--) {
     RefPtr<MediaRawData> frame(GetNextFrame(FindNextFrame()));
     if (!frame)
       break;
 
     frames->mSamples.AppendElement(frame);
   }
 
-  LOGV("GetSamples() End mSamples.Length=%u aNumSamples=%d offset=%lld"
-       " mParsedFramesDuration=%f mTotalFrameLen=%llu",
+  LOGV("GetSamples() End mSamples.Length=%" PRIuSIZE " aNumSamples=%d offset=%" PRId64
+       " mParsedFramesDuration=%f mTotalFrameLen=%" PRIu64,
        frames->mSamples.Length(), aNumSamples, GetResourceOffset(),
        mParsedFramesDuration.ToSeconds(), mTotalFrameLen);
 
   if (frames->mSamples.IsEmpty()) {
     return SamplesPromise::CreateAndReject(
       NS_ERROR_DOM_MEDIA_END_OF_STREAM, __func__);
   }
 
@@ -925,67 +926,67 @@ FlacTrackDemuxer::GetBuffered()
   // However, for now this will do.
   AutoPinned<MediaResource> stream(mSource.GetResource());
   return GetEstimatedBufferedTimeRanges(stream, duration.ToMicroseconds());
 }
 
 const flac::Frame&
 FlacTrackDemuxer::FindNextFrame()
 {
-  LOGV("FindNext() Begin offset=%lld mParsedFramesDuration=%f"
-       " mTotalFrameLen=%llu",
+  LOGV("FindNext() Begin offset=%" PRId64 " mParsedFramesDuration=%f"
+       " mTotalFrameLen=%" PRIu64,
        GetResourceOffset(), mParsedFramesDuration.ToSeconds(), mTotalFrameLen);
 
   if (mParser->FindNextFrame(mSource)) {
     // Update our current progress stats.
     mParsedFramesDuration =
       std::max(mParsedFramesDuration,
                mParser->CurrentFrame().Time() - mParser->FirstFrame().Time()
                + mParser->CurrentFrame().Duration());
     mTotalFrameLen =
       std::max<uint64_t>(mTotalFrameLen,
                          mParser->CurrentFrame().Offset()
                          - mParser->FirstFrame().Offset()
                          + mParser->CurrentFrame().Size());
 
-    LOGV("FindNext() End time=%f offset=%lld mParsedFramesDuration=%f"
-         " mTotalFrameLen=%llu",
+    LOGV("FindNext() End time=%f offset=%" PRId64 " mParsedFramesDuration=%f"
+         " mTotalFrameLen=%" PRIu64,
          mParser->CurrentFrame().Time().ToSeconds(), GetResourceOffset(),
          mParsedFramesDuration.ToSeconds(), mTotalFrameLen);
   }
 
   return mParser->CurrentFrame();
 }
 
 already_AddRefed<MediaRawData>
 FlacTrackDemuxer::GetNextFrame(const flac::Frame& aFrame)
 {
   if (!aFrame.IsValid()) {
     LOG("GetNextFrame() EOS");
     return nullptr;
   }
 
-  LOG("GetNextFrame() Begin(time=%f offset=%lld size=%u)",
+  LOG("GetNextFrame() Begin(time=%f offset=%" PRId64 " size=%u)",
       aFrame.Time().ToSeconds(), aFrame.Offset(), aFrame.Size());
 
   const int64_t offset = aFrame.Offset();
   const uint32_t size = aFrame.Size();
 
   RefPtr<MediaRawData> frame = new MediaRawData();
   frame->mOffset = offset;
 
   nsAutoPtr<MediaRawDataWriter> frameWriter(frame->CreateWriter());
   if (!frameWriter->SetSize(size)) {
     LOG("GetNext() Exit failed to allocated media buffer");
     return nullptr;
   }
 
   const uint32_t read = Read(frameWriter->Data(), offset, size);
   if (read != size) {
-    LOG("GetNextFrame() Exit read=%u frame->Size=%u", read, frame->Size());
+    LOG("GetNextFrame() Exit read=%u frame->Size=%" PRIuSIZE, read, frame->Size());
     return nullptr;
   }
 
   frame->mTime = aFrame.Time().ToMicroseconds();
   frame->mDuration = aFrame.Duration().ToMicroseconds();
   frame->mTimecode = frame->mTime;
   frame->mOffset = aFrame.Offset();
   frame->mKeyframe = true;
--- a/dom/media/fmp4/MP4Demuxer.cpp
+++ b/dom/media/fmp4/MP4Demuxer.cpp
@@ -336,27 +336,29 @@ MP4TrackDemuxer::GetNextSample()
         mp4_demuxer::H264::GetFrameType(sample);
       switch (type) {
         case mp4_demuxer::H264::FrameType::I_FRAME: MOZ_FALLTHROUGH;
         case mp4_demuxer::H264::FrameType::OTHER:
         {
           bool keyframe = type == mp4_demuxer::H264::FrameType::I_FRAME;
           if (sample->mKeyframe != keyframe) {
             NS_WARNING(nsPrintfCString("Frame incorrectly marked as %skeyframe "
-                                       "@ pts:%lld dur:%u dts:%lld",
+                                       "@ pts:%" PRId64 " dur:%" PRId64
+                                       " dts:%" PRId64,
                                        keyframe ? "" : "non-", sample->mTime,
                                        sample->mDuration, sample->mTimecode)
                          .get());
             sample->mKeyframe = keyframe;
           }
           break;
         }
         case mp4_demuxer::H264::FrameType::INVALID:
           NS_WARNING(
-            nsPrintfCString("Invalid H264 frame @ pts:%lld dur:%u dts:%lld",
+            nsPrintfCString("Invalid H264 frame @ pts:%" PRId64 " dur:%" PRId64
+                            " dts:%" PRId64,
                             sample->mTime, sample->mDuration, sample->mTimecode)
               .get());
           // We could reject the sample now, however demuxer errors are fatal.
           // So we keep the invalid frame, relying on the H264 decoder to
           // handle the error later.
           // TODO: make demuxer errors non-fatal.
           break;
       }
--- a/dom/media/gmp/GMPDecryptorParent.cpp
+++ b/dom/media/gmp/GMPDecryptorParent.cpp
@@ -1,16 +1,17 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "GMPDecryptorParent.h"
 #include "GMPContentParent.h"
 #include "MediaData.h"
+#include "mozilla/SizePrintfMacros.h"
 #include "mozilla/Unused.h"
 
 namespace mozilla {
 
 #ifdef LOG
 #undef LOG
 #endif
 
@@ -369,17 +370,17 @@ ToMediaKeyStatus(GMPMediaKeyStatus aStat
     default: return dom::MediaKeyStatus::Internal_error;
   }
 }
 
 mozilla::ipc::IPCResult
 GMPDecryptorParent::RecvBatchedKeyStatusChanged(const nsCString& aSessionId,
                                                 InfallibleTArray<GMPKeyInformation>&& aKeyInfos)
 {
-  LOGD(("GMPDecryptorParent[%p]::RecvBatchedKeyStatusChanged(sessionId='%s', KeyInfos len='%d')",
+  LOGD(("GMPDecryptorParent[%p]::RecvBatchedKeyStatusChanged(sessionId='%s', KeyInfos len='%" PRIuSIZE "')",
         this, aSessionId.get(), aKeyInfos.Length()));
 
   if (mIsOpen) {
     nsTArray<CDMKeyInfo> cdmKeyInfos(aKeyInfos.Length());
     for (uint32_t i = 0; i < aKeyInfos.Length(); i++) {
       LOGD(("GMPDecryptorParent[%p]::RecvBatchedKeyStatusChanged(keyId=%s, gmp-status=%d)",
             this, ToHexString(aKeyInfos[i].keyId()).get(), aKeyInfos[i].status()));
       // If the status is kGMPUnknown, we're going to forget(remove) that key info.
--- a/dom/media/gmp/GMPServiceChild.cpp
+++ b/dom/media/gmp/GMPServiceChild.cpp
@@ -97,17 +97,18 @@ GeckoMediaPluginServiceChild::GetContent
         // helper so that if the launch failed due to the plugin crashing,
         // we can report the crash via the crash reporter. The crash
         // handling notification will arrive shortly if the launch failed
         // due to the plugin crashing.
         self->ConnectCrashHelper(pluginId, helper);
       }
 
       if (!ok || NS_FAILED(rv)) {
-        LOGD(("GeckoMediaPluginServiceChild::GetContentParent SendLaunchGMP failed rv=%d", rv));
+        LOGD(("GeckoMediaPluginServiceChild::GetContentParent SendLaunchGMP failed rv=%" PRIu32,
+              static_cast<uint32_t>(rv)));
         holder->Reject(rv, __func__);
         return;
       }
 
       RefPtr<GMPContentParent> parent = child->GetBridgedGMPContentParent(otherProcess,
                                                                           Move(endpoint));
       if (!alreadyBridgedTo.Contains(otherProcess)) {
         parent->SetDisplayName(displayName);
--- a/dom/media/gmp/GMPServiceParent.cpp
+++ b/dom/media/gmp/GMPServiceParent.cpp
@@ -12,16 +12,17 @@
 #include "mozilla/dom/ContentParent.h"
 #include "GMPParent.h"
 #include "GMPVideoDecoderParent.h"
 #include "nsAutoPtr.h"
 #include "nsIObserverService.h"
 #include "GeckoChildProcessHost.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/ClearOnShutdown.h"
+#include "mozilla/SizePrintfMacros.h"
 #include "mozilla/SyncRunnable.h"
 #include "nsXPCOMPrivate.h"
 #include "mozilla/Services.h"
 #include "nsNativeCharsetUtils.h"
 #include "nsIConsoleService.h"
 #include "mozilla/Unused.h"
 #include "GMPDecryptorParent.h"
 #include "nsComponentManagerUtils.h"
@@ -442,17 +443,17 @@ GeckoMediaPluginServiceParent::UnloadPlu
   nsTArray<RefPtr<GMPParent>> plugins;
   {
     MutexAutoLock lock(mMutex);
     // Move all plugins references to a local array. This way mMutex won't be
     // locked when calling CloseActive (to avoid inter-locking).
     Swap(plugins, mPlugins);
   }
 
-  LOGD(("%s::%s plugins:%u", __CLASS__, __FUNCTION__,
+  LOGD(("%s::%s plugins:%" PRIuSIZE, __CLASS__, __FUNCTION__,
         plugins.Length()));
 #ifdef DEBUG
   for (const auto& plugin : plugins) {
     LOGD(("%s::%s plugin: '%s'", __CLASS__, __FUNCTION__,
           plugin->GetDisplayName().get()));
   }
 #endif
   // Note: CloseActive may be async; it could actually finish
@@ -826,17 +827,18 @@ GeckoMediaPluginServiceParent::AddOnGMPT
     LOGD(("%s::%s: %s No GMP Thread", __CLASS__, __FUNCTION__, dir.get()));
     return GenericPromise::CreateAndReject(NS_ERROR_FAILURE, __func__);
   }
   LOGD(("%s::%s: %s", __CLASS__, __FUNCTION__, dir.get()));
 
   nsCOMPtr<nsIFile> directory;
   nsresult rv = NS_NewLocalFile(aDirectory, false, getter_AddRefs(directory));
   if (NS_WARN_IF(NS_FAILED(rv))) {
-    LOGD(("%s::%s: failed to create nsIFile for dir=%s rv=%x", __CLASS__, __FUNCTION__, dir.get(), rv));
+    LOGD(("%s::%s: failed to create nsIFile for dir=%s rv=%" PRIx32,
+          __CLASS__, __FUNCTION__, dir.get(), static_cast<uint32_t>(rv)));
     return GenericPromise::CreateAndReject(NS_ERROR_FAILURE, __func__);
   }
 
   RefPtr<GMPParent> gmp = CreateGMPParent();
   if (!gmp) {
     NS_WARNING("Can't Create GMPParent");
     return GenericPromise::CreateAndReject(NS_ERROR_FAILURE, __func__);
   }
@@ -1473,17 +1475,17 @@ GeckoMediaPluginServiceParent::ForgetThi
 
   ClearNodeIdAndPlugin(filter);
 }
 
 void
 GeckoMediaPluginServiceParent::ClearRecentHistoryOnGMPThread(PRTime aSince)
 {
   MOZ_ASSERT(NS_GetCurrentThread() == mGMPThread);
-  LOGD(("%s::%s: since=%lld", __CLASS__, __FUNCTION__, (int64_t)aSince));
+  LOGD(("%s::%s: since=%" PRId64, __CLASS__, __FUNCTION__, (int64_t)aSince));
 
   struct MTimeFilter : public DirectoryFilter {
     explicit MTimeFilter(PRTime aSince)
       : mSince(aSince) {}
 
     // Return true if any files under aPath is modified after |mSince|.
     bool IsModifiedAfter(nsIFile* aPath) {
       PRTime lastModified;
--- a/dom/media/gmp/GMPStorageParent.cpp
+++ b/dom/media/gmp/GMPStorageParent.cpp
@@ -1,16 +1,17 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "GMPStorageParent.h"
 #include "GMPParent.h"
 #include "gmp-storage.h"
+#include "mozilla/SizePrintfMacros.h"
 #include "mozilla/Unused.h"
 #include "mozIGeckoMediaPluginService.h"
 
 namespace mozilla {
 
 #ifdef LOG
 #undef LOG
 #endif
@@ -114,29 +115,29 @@ GMPStorageParent::RecvRead(const nsCStri
 
   nsTArray<uint8_t> data;
   if (!mStorage->IsOpen(aRecordName)) {
     LOGD(("GMPStorageParent[%p]::RecvRead(record='%s') failed; record not open",
          this, aRecordName.get()));
     Unused << SendReadComplete(aRecordName, GMPClosedErr, data);
   } else {
     GMPErr rv = mStorage->Read(aRecordName, data);
-    LOGD(("GMPStorageParent[%p]::RecvRead(record='%s') read %d bytes rv=%d",
-      this, aRecordName.get(), data.Length(), rv));
+    LOGD(("GMPStorageParent[%p]::RecvRead(record='%s') read %" PRIuSIZE " bytes rv=%" PRIu32,
+          this, aRecordName.get(), data.Length(), static_cast<uint32_t>(rv)));
     Unused << SendReadComplete(aRecordName, rv, data);
   }
 
   return IPC_OK();
 }
 
 mozilla::ipc::IPCResult
 GMPStorageParent::RecvWrite(const nsCString& aRecordName,
                             InfallibleTArray<uint8_t>&& aBytes)
 {
-  LOGD(("GMPStorageParent[%p]::RecvWrite(record='%s') %d bytes",
+  LOGD(("GMPStorageParent[%p]::RecvWrite(record='%s') %" PRIuSIZE " bytes",
         this, aRecordName.get(), aBytes.Length()));
 
   if (mShutdown) {
     return IPC_FAIL_NO_REASON(this);
   }
 
   if (!mStorage->IsOpen(aRecordName)) {
     LOGD(("GMPStorageParent[%p]::RecvWrite(record='%s') failed record not open",
--- a/dom/media/gmp/GMPVideoDecoderParent.cpp
+++ b/dom/media/gmp/GMPVideoDecoderParent.cpp
@@ -1,15 +1,16 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "GMPVideoDecoderParent.h"
 #include "mozilla/Logging.h"
+#include "mozilla/SizePrintfMacros.h"
 #include "mozilla/Unused.h"
 #include "nsAutoRef.h"
 #include "nsThreadUtils.h"
 #include "GMPUtils.h"
 #include "GMPVideoEncodedFrameImpl.h"
 #include "GMPVideoi420FrameImpl.h"
 #include "GMPContentParent.h"
 #include "GMPMessageUtils.h"
@@ -134,17 +135,17 @@ CryptoInfo(const GMPUniquePtr<GMPVideoEn
 }
 
 nsresult
 GMPVideoDecoderParent::Decode(GMPUniquePtr<GMPVideoEncodedFrame> aInputFrame,
                               bool aMissingFrames,
                               const nsTArray<uint8_t>& aCodecSpecificInfo,
                               int64_t aRenderTimeMs)
 {
-  LOGV(("GMPVideoDecoderParent[%p]::Decode() timestamp=%lld keyframe=%d%s",
+  LOGV(("GMPVideoDecoderParent[%p]::Decode() timestamp=%" PRId64 " keyframe=%d%s",
         this, aInputFrame->TimeStamp(),
         aInputFrame->FrameType() == kGMPKeyFrame,
         CryptoInfo(aInputFrame).get()));
 
   if (!mIsOpen) {
     LOGE(("GMPVideoDecoderParent[%p]::Decode() ERROR; dead GMPVideoDecoder", this));
     NS_WARNING("Trying to use an dead GMP video decoder");
     return NS_ERROR_FAILURE;
@@ -314,26 +315,27 @@ GMPVideoDecoderParent::ActorDestroy(Acto
   mVideoHost.ActorDestroyed();
   MaybeDisconnect(aWhy == AbnormalShutdown);
 }
 
 mozilla::ipc::IPCResult
 GMPVideoDecoderParent::RecvDecoded(const GMPVideoi420FrameData& aDecodedFrame)
 {
   --mFrameCount;
-  LOGV(("GMPVideoDecoderParent[%p]::RecvDecoded() timestamp=%lld frameCount=%d",
+  LOGV(("GMPVideoDecoderParent[%p]::RecvDecoded() timestamp=%" PRId64 " frameCount=%d",
     this, aDecodedFrame.mTimestamp(), mFrameCount));
 
   if (!mCallback) {
     return IPC_FAIL_NO_REASON(this);
   }
 
   if (!GMPVideoi420FrameImpl::CheckFrameData(aDecodedFrame)) {
     LOGE(("GMPVideoDecoderParent[%p]::RecvDecoded() "
-       "timestamp=%lld decoded frame corrupt, ignoring"));
+          "timestamp=%" PRId64 " decoded frame corrupt, ignoring",
+          this, aDecodedFrame.mTimestamp()));
     return IPC_FAIL_NO_REASON(this);
   }
   auto f = new GMPVideoi420FrameImpl(aDecodedFrame, &mVideoHost);
 
   // Ignore any return code. It is OK for this to fail without killing the process.
   mCallback->Decoded(f);
 
   return IPC_OK();
--- a/dom/media/gmp/widevine-adapter/WidevineAdapter.cpp
+++ b/dom/media/gmp/widevine-adapter/WidevineAdapter.cpp
@@ -103,17 +103,17 @@ WidevineAdapter::GMPGetAPI(const char* a
              kEMEKeySystemWidevine.Length(),
              &GetCdmHost,
              decryptor));
     if (!cdm) {
       Log("WidevineAdapter::GMPGetAPI(%s, 0x%p, 0x%p, %u) this=0x%p FAILED to create cdm",
           aAPIName, aHostAPI, aPluginAPI, aDecryptorId, this);
       return GMPGenericErr;
     }
-    Log("cdm: 0x%x", cdm);
+    Log("cdm: 0x%p", cdm);
     RefPtr<CDMWrapper> wrapper(new CDMWrapper(cdm, decryptor));
     decryptor->SetCDM(wrapper, aDecryptorId);
     *aPluginAPI = decryptor;
 
   } else if (!strcmp(aAPIName, GMP_API_VIDEO_DECODER)) {
     RefPtr<CDMWrapper> wrapper = WidevineDecryptor::GetInstance(aDecryptorId);
 
     // There is a possible race condition, where the decryptor will be destroyed
--- a/dom/media/gmp/widevine-adapter/WidevineDecryptor.cpp
+++ b/dom/media/gmp/widevine-adapter/WidevineDecryptor.cpp
@@ -286,17 +286,17 @@ WidevineDecryptor::DecryptBuffer(const P
 {
   GMPBuffer* buffer = aJob.mBuffer;
   const GMPEncryptedBufferMetadata* crypto = aJob.mMetadata;
   InputBuffer sample;
   nsTArray<SubsampleEntry> subsamples;
   InitInputBuffer(crypto, buffer->Id(), buffer->Data(), buffer->Size(), sample, subsamples);
   WidevineDecryptedBlock decrypted;
   Status rv = CDM()->Decrypt(sample, &decrypted);
-  Log("Decryptor::Decrypt(timestamp=%lld) rv=%d sz=%d",
+  Log("Decryptor::Decrypt(timestamp=%" PRId64 ") rv=%d sz=%d",
       sample.timestamp, rv, decrypted.DecryptedBuffer()->Size());
   if (rv == kSuccess) {
     buffer->Resize(decrypted.DecryptedBuffer()->Size());
     memcpy(buffer->Data(),
            decrypted.DecryptedBuffer()->Data(),
            decrypted.DecryptedBuffer()->Size());
   }
   mCallback->Decrypted(buffer, ToGMPErr(rv));
@@ -324,21 +324,21 @@ WidevineDecryptor::DecryptingComplete()
   sDecryptors.erase(mInstanceId);
   mCallback = nullptr;
   Release();
 }
 
 class WidevineBuffer : public cdm::Buffer {
 public:
   explicit WidevineBuffer(size_t aSize) {
-    Log("WidevineBuffer(size=" PRIuSIZE ") created", aSize);
+    Log("WidevineBuffer(size=%" PRIuSIZE ") created", aSize);
     mBuffer.SetLength(aSize);
   }
   ~WidevineBuffer() override {
-    Log("WidevineBuffer(size=" PRIuSIZE ") destroyed", Size());
+    Log("WidevineBuffer(size=%" PRIu32 ") destroyed", Size());
   }
   void Destroy() override { delete this; }
   uint32_t Capacity() const override { return mBuffer.Length(); };
   uint8_t* Data() override { return mBuffer.Elements(); }
   void SetSize(uint32_t aSize) override { mBuffer.SetLength(aSize); }
   uint32_t Size() const override { return mBuffer.Length(); }
 
 private:
@@ -374,17 +374,17 @@ private:
   RefPtr<WidevineDecryptor> mDecryptor;
   RefPtr<CDMWrapper> mCDM;
   void* mContext;
 };
 
 void
 WidevineDecryptor::SetTimer(int64_t aDelayMs, void* aContext)
 {
-  Log("Decryptor::SetTimer(delay_ms=%lld, context=0x%x)", aDelayMs, aContext);
+  Log("Decryptor::SetTimer(delay_ms=%" PRId64 ", context=0x%p)", aDelayMs, aContext);
   if (mCDM) {
     GMPSetTimerOnMainThread(new TimerTask(this, mCDM, aContext), aDelayMs);
   }
 }
 
 Time
 WidevineDecryptor::GetCurrentWallTime()
 {
--- a/dom/media/gmp/widevine-adapter/WidevineVideoDecoder.cpp
+++ b/dom/media/gmp/widevine-adapter/WidevineVideoDecoder.cpp
@@ -136,17 +136,17 @@ WidevineVideoDecoder::Decode(GMPVideoEnc
   if (raw->mKeyframe
       && !subsamples.IsEmpty()
       && mCodecType == kGMPVideoCodecH264) {
     subsamples[0].clear_bytes += mAnnexB->Length();
   }
 
   WidevineVideoFrame frame;
   Status rv = CDM()->DecryptAndDecodeFrame(sample, &frame);
-  Log("WidevineVideoDecoder::Decode(timestamp=%lld) rv=%d", sample.timestamp,
+  Log("WidevineVideoDecoder::Decode(timestamp=%" PRId64 ") rv=%d", sample.timestamp,
       rv);
 
   // Destroy frame, so that the shmem is now free to be used to return
   // output to the Gecko process.
   aInputFrame->Destroy();
   aInputFrame = nullptr;
 
   if (rv == kSuccess) {
--- a/dom/media/gmp/widevine-adapter/WidevineVideoFrame.cpp
+++ b/dom/media/gmp/widevine-adapter/WidevineVideoFrame.cpp
@@ -1,16 +1,17 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "WidevineVideoFrame.h"
 
 #include "WidevineUtils.h"
+#include "mozilla/IntegerPrintfMacros.h"
 
 using namespace cdm;
 
 namespace mozilla {
 
 WidevineVideoFrame::WidevineVideoFrame()
   : mFormat(kUnknownVideoFormat)
   , mSize(0,0)
@@ -108,17 +109,17 @@ uint32_t
 WidevineVideoFrame::Stride(cdm::VideoFrame::VideoPlane aPlane)
 {
   return mPlaneStrides[aPlane];
 }
 
 void
 WidevineVideoFrame::SetTimestamp(int64_t timestamp)
 {
-  Log("WidevineVideoFrame::SetTimestamp(%lld) this=%p", timestamp, this);
+  Log("WidevineVideoFrame::SetTimestamp(%" PRId64 ") this=%p", timestamp, this);
   mTimestamp = timestamp;
 }
 
 int64_t
 WidevineVideoFrame::Timestamp() const
 {
   return mTimestamp;
 }
--- a/dom/media/mediasink/DecodedAudioDataSink.cpp
+++ b/dom/media/mediasink/DecodedAudioDataSink.cpp
@@ -7,16 +7,17 @@
 #include "nsPrintfCString.h"
 #include "MediaQueue.h"
 #include "DecodedAudioDataSink.h"
 #include "VideoUtils.h"
 #include "AudioConverter.h"
 
 #include "mozilla/CheckedInt.h"
 #include "mozilla/DebugOnly.h"
+#include "mozilla/IntegerPrintfMacros.h"
 #include "MediaPrefs.h"
 
 namespace mozilla {
 
 extern LazyLogModule gMediaDecoderLog;
 #define SINK_LOG(msg, ...) \
   MOZ_LOG(gMediaDecoderLog, LogLevel::Debug, \
     ("DecodedAudioDataSink=%p " msg, this, ##__VA_ARGS__))
@@ -302,17 +303,17 @@ DecodedAudioDataSink::PopFrames(uint32_t
     }
     MOZ_ASSERT(mCurrentData->mFrames > 0);
     mProcessedQueueLength -=
       FramesToUsecs(mCurrentData->mFrames, mOutputRate).value();
   }
 
   auto framesToPop = std::min(aFrames, mCursor->Available());
 
-  SINK_LOG_V("playing audio at time=%lld offset=%u length=%u",
+  SINK_LOG_V("playing audio at time=%" PRId64 " offset=%u length=%u",
              mCurrentData->mTime, mCurrentData->mFrames - mCursor->Available(), framesToPop);
 
   UniquePtr<AudioStream::Chunk> chunk =
     MakeUnique<Chunk>(mCurrentData, framesToPop, mCursor->Ptr());
 
   {
     MonitorAutoLock mon(mMonitor);
     mWritten += framesToPop;
--- a/dom/media/mediasink/DecodedStream.cpp
+++ b/dom/media/mediasink/DecodedStream.cpp
@@ -225,18 +225,18 @@ DecodedStreamData::Forget()
 {
   mListener->Forget();
 }
 
 nsCString
 DecodedStreamData::GetDebugInfo()
 {
   return nsPrintfCString(
-    "DecodedStreamData=%p mPlaying=%d mAudioFramesWritten=%lld "
-    "mNextAudioTime=%lld mNextVideoTime=%lld mHaveSentFinish=%d "
+    "DecodedStreamData=%p mPlaying=%d mAudioFramesWritten=%" PRId64
+    " mNextAudioTime=%" PRId64 " mNextVideoTime=%" PRId64 " mHaveSentFinish=%d "
     "mHaveSentFinishAudio=%d mHaveSentFinishVideo=%d",
     this, mPlaying, mAudioFramesWritten, mNextAudioTime, mNextVideoTime,
     mHaveSentFinish, mHaveSentFinishAudio, mHaveSentFinishVideo);
 }
 
 DecodedStream::DecodedStream(AbstractThread* aOwnerThread,
                              AbstractThread* aMainThread,
                              MediaQueue<MediaData>& aAudioQueue,
@@ -776,14 +776,14 @@ DecodedStream::DisconnectListener()
   mVideoFinishListener.Disconnect();
 }
 
 nsCString
 DecodedStream::GetDebugInfo()
 {
   AssertOwnerThread();
   return nsPrintfCString(
-    "DecodedStream=%p mStartTime=%lld mLastOutputTime=%lld mPlaying=%d mData=%p",
+    "DecodedStream=%p mStartTime=%" PRId64 " mLastOutputTime=%" PRId64 " mPlaying=%d mData=%p",
     this, mStartTime.valueOr(-1), mLastOutputTime, mPlaying, mData.get())
     + (mData ? nsCString("\n") + mData->GetDebugInfo() : nsCString());
 }
 
 } // namespace mozilla
--- a/dom/media/mediasink/VideoSink.cpp
+++ b/dom/media/mediasink/VideoSink.cpp
@@ -3,16 +3,19 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "MediaQueue.h"
 #include "VideoSink.h"
 #include "MediaPrefs.h"
 
+#include "mozilla/IntegerPrintfMacros.h"
+#include "mozilla/SizePrintfMacros.h"
+
 namespace mozilla {
 
 extern LazyLogModule gMediaDecoderLog;
 
 #undef FMT
 
 #define FMT(x, ...) "VideoSink=%p " x, this, ##__VA_ARGS__
 #define VSINK_LOG(x, ...)   MOZ_LOG(gMediaDecoderLog, LogLevel::Debug,   (FMT(x, ##__VA_ARGS__)))
@@ -389,17 +392,17 @@ VideoSink::RenderVideoFrames(int32_t aMa
     }
 
     ImageContainer::NonOwningImage* img = images.AppendElement();
     img->mTimeStamp = t;
     img->mImage = frame->mImage;
     img->mFrameID = frame->mFrameID;
     img->mProducerID = mProducerID;
 
-    VSINK_LOG_V("playing video frame %lld (id=%x) (vq-queued=%i)",
+    VSINK_LOG_V("playing video frame %" PRId64 " (id=%x) (vq-queued=%" PRIuSIZE ")",
                 frame->mTime, frame->mFrameID, VideoQueue().GetSize());
   }
   mContainer->SetCurrentFrames(frames[0]->As<VideoData>()->mDisplay, images);
 }
 
 void
 VideoSink::UpdateRenderedVideoFrames()
 {
@@ -416,17 +419,17 @@ VideoSink::UpdateRenderedVideoFrames()
   while (VideoQueue().GetSize() > mMinVideoQueueSize &&
          clockTime >= VideoQueue().PeekFront()->GetEndTime()) {
     RefPtr<MediaData> frame = VideoQueue().PopFront();
     lastFrameEndTime = frame->GetEndTime();
     if (frame->As<VideoData>()->IsSentToCompositor()) {
       mFrameStats.NotifyPresentedFrame();
     } else {
       mFrameStats.NotifyDecodedFrames({ 0, 0, 1 });
-      VSINK_LOG_V("discarding video frame mTime=%lld clock_time=%lld",
+      VSINK_LOG_V("discarding video frame mTime=%" PRId64 " clock_time=%" PRId64,
                   frame->mTime, clockTime);
     }
   }
 
   // The presentation end time of the last video frame displayed is either
   // the end time of the current frame, or if we dropped all frames in the
   // queue, the end time of the last frame we removed from the queue.
   RefPtr<MediaData> currentFrame = VideoQueue().PeekFront();
@@ -471,18 +474,18 @@ VideoSink::MaybeResolveEndPromise()
   }
 }
 
 nsCString
 VideoSink::GetDebugInfo()
 {
   AssertOwnerThread();
   return nsPrintfCString(
-    "IsStarted=%d IsPlaying=%d, VideoQueue: finished=%d size=%d, "
-    "mVideoFrameEndTime=%lld mHasVideo=%d mVideoSinkEndRequest.Exists()=%d "
+    "IsStarted=%d IsPlaying=%d, VideoQueue: finished=%d size=%" PRIuSIZE ", "
+    "mVideoFrameEndTime=%" PRId64 " mHasVideo=%d mVideoSinkEndRequest.Exists()=%d "
     "mEndPromiseHolder.IsEmpty()=%d\n",
     IsStarted(), IsPlaying(), VideoQueue().IsFinished(), VideoQueue().GetSize(),
     mVideoFrameEndTime, mHasVideo, mVideoSinkEndRequest.Exists(), mEndPromiseHolder.IsEmpty())
     + mAudioSink->GetDebugInfo();
 }
 
 } // namespace media
 } // namespace mozilla
--- a/dom/media/mediasource/ContainerParser.cpp
+++ b/dom/media/mediasource/ContainerParser.cpp
@@ -3,17 +3,19 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "ContainerParser.h"
 
 #include "WebMBufferedParser.h"
 #include "mozilla/EndianUtils.h"
+#include "mozilla/IntegerPrintfMacros.h"
 #include "mozilla/ErrorResult.h"
+#include "mozilla/SizePrintfMacros.h"
 #include "mp4_demuxer/MoofParser.h"
 #include "mozilla/Logging.h"
 #include "mozilla/Maybe.h"
 #include "MediaData.h"
 #ifdef MOZ_FMP4
 #include "MP4Stream.h"
 #include "mp4_demuxer/AtomType.h"
 #include "mp4_demuxer/ByteReader.h"
@@ -37,29 +39,29 @@ ContainerParser::ContainerParser(const M
 {
 }
 
 ContainerParser::~ContainerParser() = default;
 
 MediaResult
 ContainerParser::IsInitSegmentPresent(MediaByteBuffer* aData)
 {
-  MSE_DEBUG(ContainerParser, "aLength=%u [%x%x%x%x]",
+  MSE_DEBUG(ContainerParser, "aLength=%" PRIuSIZE " [%x%x%x%x]",
             aData->Length(),
             aData->Length() > 0 ? (*aData)[0] : 0,
             aData->Length() > 1 ? (*aData)[1] : 0,
             aData->Length() > 2 ? (*aData)[2] : 0,
             aData->Length() > 3 ? (*aData)[3] : 0);
   return NS_ERROR_NOT_AVAILABLE;
 }
 
 MediaResult
 ContainerParser::IsMediaSegmentPresent(MediaByteBuffer* aData)
 {
-  MSE_DEBUG(ContainerParser, "aLength=%u [%x%x%x%x]",
+  MSE_DEBUG(ContainerParser, "aLength=%" PRIuSIZE " [%x%x%x%x]",
             aData->Length(),
             aData->Length() > 0 ? (*aData)[0] : 0,
             aData->Length() > 1 ? (*aData)[1] : 0,
             aData->Length() > 2 ? (*aData)[2] : 0,
             aData->Length() > 3 ? (*aData)[3] : 0);
   return NS_ERROR_NOT_AVAILABLE;
 }
 
@@ -230,17 +232,17 @@ public:
         MOZ_ASSERT(mParser.mInitEndOffset <= mResource->GetLength());
         if (!mInitData->SetLength(mParser.mInitEndOffset, fallible)) {
           // Super unlikely OOM
           return NS_ERROR_OUT_OF_MEMORY;
         }
         mCompleteInitSegmentRange = MediaByteRange(0, mParser.mInitEndOffset);
         char* buffer = reinterpret_cast<char*>(mInitData->Elements());
         mResource->ReadFromCache(buffer, 0, mParser.mInitEndOffset);
-        MSE_DEBUG(WebMContainerParser, "Stashed init of %u bytes.",
+        MSE_DEBUG(WebMContainerParser, "Stashed init of %" PRId64 " bytes.",
                   mParser.mInitEndOffset);
         mResource = nullptr;
       } else {
         MSE_DEBUG(WebMContainerParser, "Incomplete init found.");
       }
       mHasInitData = true;
     }
     mOffset += aData->Length();
@@ -256,17 +258,17 @@ public:
     bool foundNewCluster = false;
     while (mapping[0].mSyncOffset != mapping[endIdx].mSyncOffset) {
       endIdx -= 1;
       foundNewCluster = true;
     }
 
     int32_t completeIdx = endIdx;
     while (completeIdx >= 0 && mOffset < mapping[completeIdx].mEndOffset) {
-      MSE_DEBUG(WebMContainerParser, "block is incomplete, missing: %lld",
+      MSE_DEBUG(WebMContainerParser, "block is incomplete, missing: %" PRId64,
                 mapping[completeIdx].mEndOffset - mOffset);
       completeIdx -= 1;
     }
 
     // Save parsed blocks for which we do not have all data yet.
     mOverlappedMapping.AppendElements(mapping.Elements() + completeIdx + 1,
                                       mapping.Length() - completeIdx - 1);
 
@@ -312,17 +314,18 @@ public:
 
     uint64_t frameDuration =
       (completeIdx + 1u < mapping.Length())
       ? mapping[completeIdx + 1].mTimecode - mapping[completeIdx].mTimecode
       : mapping[completeIdx].mTimecode - previousMapping.ref().mTimecode;
     aStart = mapping[0].mTimecode / NS_PER_USEC;
     aEnd = (mapping[completeIdx].mTimecode + frameDuration) / NS_PER_USEC;
 
-    MSE_DEBUG(WebMContainerParser, "[%lld, %lld] [fso=%lld, leo=%lld, l=%u processedIdx=%u fs=%lld]",
+    MSE_DEBUG(WebMContainerParser, "[%" PRId64 ", %" PRId64 "] [fso=%" PRId64
+              ", leo=%" PRId64 ", l=%" PRIuSIZE " processedIdx=%u fs=%" PRId64 "]",
               aStart, aEnd, mapping[0].mSyncOffset,
               mapping[completeIdx].mEndOffset, mapping.Length(), completeIdx,
               mCompleteMediaSegmentRange.mEnd);
 
     return NS_OK;
   }
 
   int64_t GetRoundingError() override
@@ -497,17 +500,17 @@ public:
       if (range.Length()) {
         mCompleteInitSegmentRange = range;
         if (!mInitData->SetLength(range.Length(), fallible)) {
           // Super unlikely OOM
           return NS_ERROR_OUT_OF_MEMORY;
         }
         char* buffer = reinterpret_cast<char*>(mInitData->Elements());
         mResource->ReadFromCache(buffer, range.mStart, range.Length());
-        MSE_DEBUG(MP4ContainerParser ,"Stashed init of %u bytes.",
+        MSE_DEBUG(MP4ContainerParser ,"Stashed init of %" PRIu64 " bytes.",
                   range.Length());
       } else {
         MSE_DEBUG(MP4ContainerParser, "Incomplete init found.");
       }
       mHasInitData = true;
     }
 
     mp4_demuxer::Interval<mp4_demuxer::Microseconds> compositionRange =
@@ -524,17 +527,17 @@ public:
       return NS_ERROR_OUT_OF_MEMORY;
     }
 
     if (compositionRange.IsNull()) {
       return NS_ERROR_NOT_AVAILABLE;
     }
     aStart = compositionRange.start;
     aEnd = compositionRange.end;
-    MSE_DEBUG(MP4ContainerParser, "[%lld, %lld]",
+    MSE_DEBUG(MP4ContainerParser, "[%" PRId64 ", %" PRId64 "]",
               aStart, aEnd);
     return NS_OK;
   }
 
   // Gaps of up to 35ms (marginally longer than a single frame at 30fps) are considered
   // to be sequential frames.
   int64_t GetRoundingError() override
   {
@@ -674,17 +677,17 @@ public:
     }
     mCompleteMediaSegmentRange = MediaByteRange(header.header_length,
                                                 header.frame_length);
     // The ADTS MediaSource Byte Stream Format document doesn't
     // define media header. Just treat it the same as the whole
     // media segment.
     mCompleteMediaHeaderRange = mCompleteMediaSegmentRange;
 
-    MSE_DEBUG(ADTSContainerParser, "[%lld, %lld]",
+    MSE_DEBUG(ADTSContainerParser, "[%" PRId64 ", %" PRId64 "]",
               aStart, aEnd);
     // We don't update timestamps, regardless.
     return NS_ERROR_NOT_AVAILABLE;
   }
 
   // Audio shouldn't have gaps.
   // Especially when we generate the timestamps ourselves.
   int64_t GetRoundingError() override
--- a/dom/media/mediasource/MediaSource.cpp
+++ b/dom/media/mediasource/MediaSource.cpp
@@ -330,17 +330,17 @@ MediaSource::EndOfStream(const Optional<
     aRv.Throw(NS_ERROR_DOM_TYPE_ERR);
   }
 }
 
 void
 MediaSource::EndOfStream(const MediaResult& aError)
 {
   MOZ_ASSERT(NS_IsMainThread());
-  MSE_API("EndOfStream(aError=%d)", aError.Code());
+  MSE_API("EndOfStream(aError=%" PRId32")", static_cast<uint32_t>(aError.Code()));
 
   SetReadyState(MediaSourceReadyState::Ended);
   mSourceBuffers->Ended();
   mDecoder->DecodeError(aError);
 }
 
 /* static */ bool
 MediaSource::IsTypeSupported(const GlobalObject& aOwner, const nsAString& aType)
@@ -470,17 +470,18 @@ MediaSource::MediaSource(nsPIDOMWindowIn
           aWindow, mSourceBuffers.get(), mActiveSourceBuffers.get());
 }
 
 void
 MediaSource::SetReadyState(MediaSourceReadyState aState)
 {
   MOZ_ASSERT(NS_IsMainThread());
   MOZ_ASSERT(aState != mReadyState);
-  MSE_DEBUG("SetReadyState(aState=%d) mReadyState=%d", aState, mReadyState);
+  MSE_DEBUG("SetReadyState(aState=%" PRIu32 ") mReadyState=%" PRIu32,
+            static_cast<uint32_t>(aState), static_cast<uint32_t>(mReadyState));
 
   MediaSourceReadyState oldState = mReadyState;
   mReadyState = aState;
 
   if (mReadyState == MediaSourceReadyState::Open &&
       (oldState == MediaSourceReadyState::Closed ||
        oldState == MediaSourceReadyState::Ended)) {
     QueueAsyncSimpleEvent("sourceopen");
--- a/dom/media/mediasource/MediaSourceDemuxer.cpp
+++ b/dom/media/mediasource/MediaSourceDemuxer.cpp
@@ -249,31 +249,31 @@ MediaSourceDemuxer::~MediaSourceDemuxer(
 void
 MediaSourceDemuxer::GetMozDebugReaderData(nsACString& aString)
 {
   MonitorAutoLock mon(mMonitor);
   nsAutoCString result;
   result += nsPrintfCString("Dumping data for demuxer %p:\n", this);
   if (mAudioTrack) {
     result += nsPrintfCString("\tDumping Audio Track Buffer(%s): - mLastAudioTime: %f\n"
-                              "\t\tNumSamples:%u Size:%u Evictable:%u NextGetSampleIndex:%u NextInsertionIndex:%d\n",
+                              "\t\tNumSamples:%" PRIuSIZE " Size:%u Evictable:%u NextGetSampleIndex:%u NextInsertionIndex:%d\n",
                               mAudioTrack->mAudioTracks.mInfo->mMimeType.get(),
                               mAudioTrack->mAudioTracks.mNextSampleTime.ToSeconds(),
                               mAudioTrack->mAudioTracks.mBuffers[0].Length(),
                               mAudioTrack->mAudioTracks.mSizeBuffer,
                               mAudioTrack->Evictable(TrackInfo::kAudioTrack),
                               mAudioTrack->mAudioTracks.mNextGetSampleIndex.valueOr(-1),
                               mAudioTrack->mAudioTracks.mNextInsertionIndex.valueOr(-1));
 
     result += nsPrintfCString("\t\tBuffered: ranges=%s\n",
                               DumpTimeRanges(mAudioTrack->SafeBuffered(TrackInfo::kAudioTrack)).get());
   }
   if (mVideoTrack) {
     result += nsPrintfCString("\tDumping Video Track Buffer(%s) - mLastVideoTime: %f\n"
-                              "\t\tNumSamples:%u Size:%u Evictable:%u NextGetSampleIndex:%u NextInsertionIndex:%d\n",
+                              "\t\tNumSamples:%" PRIuSIZE " Size:%u Evictable:%u NextGetSampleIndex:%u NextInsertionIndex:%d\n",
                               mVideoTrack->mVideoTracks.mInfo->mMimeType.get(),
                               mVideoTrack->mVideoTracks.mNextSampleTime.ToSeconds(),
                               mVideoTrack->mVideoTracks.mBuffers[0].Length(),
                               mVideoTrack->mVideoTracks.mSizeBuffer,
                               mVideoTrack->Evictable(TrackInfo::kVideoTrack),
                               mVideoTrack->mVideoTracks.mNextGetSampleIndex.valueOr(-1),
                               mVideoTrack->mVideoTracks.mNextInsertionIndex.valueOr(-1));
 
--- a/dom/media/mediasource/ResourceQueue.cpp
+++ b/dom/media/mediasource/ResourceQueue.cpp
@@ -3,18 +3,20 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "ResourceQueue.h"
 #include "nsDeque.h"
 #include "MediaData.h"
 #include "mozilla/ErrorResult.h"
+#include "mozilla/IntegerPrintfMacros.h"
 #include "mozilla/Logging.h"
 #include "mozilla/Sprintf.h"
+#include "mozilla/SizePrintfMacros.h"
 
 extern mozilla::LogModule* GetSourceBufferResourceLog();
 
 #define SBR_DEBUG(arg, ...) MOZ_LOG(GetSourceBufferResourceLog(), mozilla::LogLevel::Debug, ("ResourceQueue(%p)::%s: " arg, this, __func__, ##__VA_ARGS__))
 #define SBR_DEBUGV(arg, ...) MOZ_LOG(GetSourceBufferResourceLog(), mozilla::LogLevel::Verbose, ("ResourceQueue(%p)::%s: " arg, this, __func__, ##__VA_ARGS__))
 
 namespace mozilla {
 
@@ -85,27 +87,27 @@ ResourceQueue::AppendItem(MediaByteBuffe
   mLogicalLength += aData->Length();
   Push(new ResourceItem(aData));
 }
 
 uint32_t
 ResourceQueue::Evict(uint64_t aOffset, uint32_t aSizeToEvict,
                      ErrorResult& aRv)
 {
-  SBR_DEBUG("Evict(aOffset=%llu, aSizeToEvict=%u)",
+  SBR_DEBUG("Evict(aOffset=%" PRIu64 ", aSizeToEvict=%u)",
             aOffset, aSizeToEvict);
   return EvictBefore(std::min(aOffset, mOffset + (uint64_t)aSizeToEvict), aRv);
 }
 
 uint32_t ResourceQueue::EvictBefore(uint64_t aOffset, ErrorResult& aRv)
 {
-  SBR_DEBUG("EvictBefore(%llu)", aOffset);
+  SBR_DEBUG("EvictBefore(%" PRIu64 ")", aOffset);
   uint32_t evicted = 0;
   while (ResourceItem* item = ResourceAt(0)) {
-    SBR_DEBUG("item=%p length=%d offset=%llu",
+    SBR_DEBUG("item=%p length=%" PRIuSIZE " offset=%" PRIu64,
               item, item->mData->Length(), mOffset);
     if (item->mData->Length() + mOffset >= aOffset) {
       if (aOffset <= mOffset) {
         break;
       }
       uint32_t offset = aOffset - mOffset;
       mOffset += offset;
       evicted += offset;
@@ -128,17 +130,17 @@ uint32_t ResourceQueue::EvictBefore(uint
 }
 
 uint32_t
 ResourceQueue::EvictAll()
 {
   SBR_DEBUG("EvictAll()");
   uint32_t evicted = 0;
   while (ResourceItem* item = ResourceAt(0)) {
-    SBR_DEBUG("item=%p length=%d offset=%llu",
+    SBR_DEBUG("item=%p length=%" PRIuSIZE " offset=%" PRIu64,
               item, item->mData->Length(), mOffset);
     mOffset += item->mData->Length();
     evicted += item->mData->Length();
     delete PopFront();
   }
   return evicted;
 }
 
--- a/dom/media/mediasource/SourceBuffer.cpp
+++ b/dom/media/mediasource/SourceBuffer.cpp
@@ -45,17 +45,17 @@ using media::TimeUnit;
 typedef SourceBufferAttributes::AppendState AppendState;
 
 namespace dom {
 
 void
 SourceBuffer::SetMode(SourceBufferAppendMode aMode, ErrorResult& aRv)
 {
   MOZ_ASSERT(NS_IsMainThread());
-  MSE_API("SetMode(aMode=%d)", aMode);
+  MSE_API("SetMode(aMode=%" PRIu32 ")", static_cast<uint32_t>(aMode));
   if (!IsAttached() || mUpdating) {
     aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
     return;
   }
   if (mCurrentAttributes.mGenerateTimestamps &&
       aMode == SourceBufferAppendMode::Segments) {
     aRv.Throw(NS_ERROR_DOM_TYPE_ERR);
     return;
--- a/dom/media/mediasource/SourceBufferResource.cpp
+++ b/dom/media/mediasource/SourceBufferResource.cpp
@@ -6,16 +6,17 @@
 
 #include "SourceBufferResource.h"
 
 #include <algorithm>
 
 #include "nsISeekableStream.h"
 #include "nsISupports.h"
 #include "mozilla/Logging.h"
+#include "mozilla/SizePrintfMacros.h"
 #include "MediaData.h"
 
 mozilla::LogModule* GetSourceBufferResourceLog()
 {
   static mozilla::LazyLogModule sLogModule("SourceBufferResource");
   return sLogModule;
 }
 
@@ -33,17 +34,17 @@ SourceBufferResource::Close()
   mClosed = true;
   mon.NotifyAll();
   return NS_OK;
 }
 
 nsresult
 SourceBufferResource::ReadAt(int64_t aOffset, char* aBuffer, uint32_t aCount, uint32_t* aBytes)
 {
-  SBR_DEBUG("ReadAt(aOffset=%lld, aBuffer=%p, aCount=%u, aBytes=%p)",
+  SBR_DEBUG("ReadAt(aOffset=%" PRId64 ", aBuffer=%p, aCount=%u, aBytes=%p)",
             aOffset, aBytes, aCount, aBytes);
   ReentrantMonitorAutoEnter mon(mMonitor);
   return ReadAtInternal(aOffset, aBuffer, aCount, aBytes, /* aMayBlock = */ true);
 }
 
 nsresult
 SourceBufferResource::ReadAtInternal(int64_t aOffset, char* aBuffer, uint32_t aCount, uint32_t* aBytes,
                                      bool aMayBlock)
@@ -73,64 +74,64 @@ SourceBufferResource::ReadAtInternal(int
 
   uint32_t available = GetLength() - aOffset;
   uint32_t count = std::min(aCount, available);
 
   // Keep the position of the last read to have Tell() approximately give us
   // the position we're up to in the stream.
   mOffset = aOffset + count;
 
-  SBR_DEBUGV("offset=%llu GetLength()=%u available=%u count=%u mEnded=%d",
+  SBR_DEBUGV("offset=%" PRId64 " GetLength()=%" PRId64 " available=%u count=%u mEnded=%d",
              aOffset, GetLength(), available, count, mEnded);
   if (available == 0) {
     SBR_DEBUGV("reached EOF");
     *aBytes = 0;
     return NS_OK;
   }
 
   mInputBuffer.CopyData(aOffset, count, aBuffer);
   *aBytes = count;
 
   return NS_OK;
 }
 
 nsresult
 SourceBufferResource::ReadFromCache(char* aBuffer, int64_t aOffset, uint32_t aCount)
 {
-  SBR_DEBUG("ReadFromCache(aBuffer=%p, aOffset=%lld, aCount=%u)",
+  SBR_DEBUG("ReadFromCache(aBuffer=%p, aOffset=%" PRId64 ", aCount=%u)",
             aBuffer, aOffset, aCount);
   ReentrantMonitorAutoEnter mon(mMonitor);
   uint32_t bytesRead;
   nsresult rv = ReadAtInternal(aOffset, aBuffer, aCount, &bytesRead, /* aMayBlock = */ false);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // ReadFromCache return failure if not all the data is cached.
   return bytesRead == aCount ? NS_OK : NS_ERROR_FAILURE;
 }
 
 uint32_t
 SourceBufferResource::EvictData(uint64_t aPlaybackOffset, int64_t aThreshold,
                                 ErrorResult& aRv)
 {
-  SBR_DEBUG("EvictData(aPlaybackOffset=%llu,"
-            "aThreshold=%u)", aPlaybackOffset, aThreshold);
+  SBR_DEBUG("EvictData(aPlaybackOffset=%" PRIu64 ","
+            "aThreshold=%" PRId64 ")", aPlaybackOffset, aThreshold);
   ReentrantMonitorAutoEnter mon(mMonitor);
   uint32_t result = mInputBuffer.Evict(aPlaybackOffset, aThreshold, aRv);
   if (result > 0) {
     // Wake up any waiting threads in case a ReadInternal call
     // is now invalid.
     mon.NotifyAll();
   }
   return result;
 }
 
 void
 SourceBufferResource::EvictBefore(uint64_t aOffset, ErrorResult& aRv)
 {
-  SBR_DEBUG("EvictBefore(aOffset=%llu)", aOffset);
+  SBR_DEBUG("EvictBefore(aOffset=%" PRIu64 ")", aOffset);
   ReentrantMonitorAutoEnter mon(mMonitor);
 
   mInputBuffer.EvictBefore(aOffset, aRv);
 
   // Wake up any waiting threads in case a ReadInternal call
   // is now invalid.
   mon.NotifyAll();
 }
@@ -141,17 +142,17 @@ SourceBufferResource::EvictAll()
   SBR_DEBUG("EvictAll()");
   ReentrantMonitorAutoEnter mon(mMonitor);
   return mInputBuffer.EvictAll();
 }
 
 void
 SourceBufferResource::AppendData(MediaByteBuffer* aData)
 {
-  SBR_DEBUG("AppendData(aData=%p, aLength=%u)",
+  SBR_DEBUG("AppendData(aData=%p, aLength=%" PRIuSIZE ")",
             aData->Elements(), aData->Length());
   ReentrantMonitorAutoEnter mon(mMonitor);
   mInputBuffer.AppendItem(aData);
   mEnded = false;
   mon.NotifyAll();
 }
 
 void
--- a/dom/media/mediasource/TrackBuffersManager.cpp
+++ b/dom/media/mediasource/TrackBuffersManager.cpp
@@ -4,16 +4,17 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "TrackBuffersManager.h"
 #include "ContainerParser.h"
 #include "MediaSourceDemuxer.h"
 #include "MediaSourceUtils.h"
 #include "mozilla/Preferences.h"
+#include "mozilla/SizePrintfMacros.h"
 #include "mozilla/StateMirroring.h"
 #include "SourceBufferResource.h"
 #include "SourceBuffer.h"
 #include "WebMDemuxer.h"
 #include "SourceBufferTask.h"
 
 #ifdef MOZ_FMP4
 #include "MP4Demuxer.h"
@@ -113,17 +114,17 @@ TrackBuffersManager::~TrackBuffersManage
   ShutdownDemuxers();
 }
 
 RefPtr<TrackBuffersManager::AppendPromise>
 TrackBuffersManager::AppendData(MediaByteBuffer* aData,
                                 const SourceBufferAttributes& aAttributes)
 {
   MOZ_ASSERT(NS_IsMainThread());
-  MSE_DEBUG("Appending %lld bytes", aData->Length());
+  MSE_DEBUG("Appending %" PRIuSIZE " bytes", aData->Length());
 
   mEnded = false;
 
   return InvokeAsync<RefPtr<MediaByteBuffer>, SourceBufferAttributes&&>(
            GetTaskQueue(), this, __func__,
            &TrackBuffersManager::DoAppendData, aData, aAttributes);
 }
 
@@ -269,18 +270,18 @@ TrackBuffersManager::EvictData(const Tim
     // We're adding more data than we can hold.
     return EvictDataResult::BUFFER_FULL;
   }
   const int64_t toEvict = GetSize() + aSize - EvictionThreshold();
 
   const uint32_t canEvict =
     Evictable(HasVideo() ? TrackInfo::kVideoTrack : TrackInfo::kAudioTrack);
 
-  MSE_DEBUG("currentTime=%lld buffered=%lldkB, eviction threshold=%ukB, "
-            "evict=%lldkB canevict=%ukB",
+  MSE_DEBUG("currentTime=%" PRId64 " buffered=%" PRId64 "kB, eviction threshold=%" PRId64 "kB, "
+            "evict=%" PRId64 "kB canevict=%" PRIu32 "kB",
             aPlaybackTime.ToMicroseconds(), GetSize() / 1024,
             EvictionThreshold() / 1024, toEvict / 1024, canEvict / 1024);
 
   if (toEvict <= 0) {
     mEvictionState = EvictionState::NO_EVICTION_NEEDED;
     return EvictDataResult::NO_DATA_EVICTED;
   }
 
@@ -292,17 +293,17 @@ TrackBuffersManager::EvictData(const Tim
     // However, the current appendBuffer will fail as we can't know ahead of
     // time if the eviction will later succeed.
     result = EvictDataResult::BUFFER_FULL;
   } else {
     mEvictionState = EvictionState::EVICTION_NEEDED;
     result = EvictDataResult::NO_DATA_EVICTED;
   }
   MSE_DEBUG(
-    "Reached our size limit, schedule eviction of %lld bytes (%s)", toEvict,
+    "Reached our size limit, schedule eviction of %" PRId64 " bytes (%s)", toEvict,
     result == EvictDataResult::BUFFER_FULL ? "buffer full" : "no data evicted");
   QueueTask(new EvictDataTask(aPlaybackTime, toEvict));
 
   return result;
 }
 
 TimeIntervals
 TrackBuffersManager::Buffered() const
@@ -449,17 +450,17 @@ TrackBuffersManager::DoEvictData(const T
       break;
     }
     partialEvict += frame->ComputedSizeOfIncludingThis();
   }
 
   const int64_t finalSize = mSizeSourceBuffer - aSizeToEvict;
 
   if (lastKeyFrameIndex > 0) {
-    MSE_DEBUG("Step1. Evicting %lld bytes prior currentTime",
+    MSE_DEBUG("Step1. Evicting %" PRId64 " bytes prior currentTime",
               aSizeToEvict - toEvict);
     CodedFrameRemoval(
       TimeInterval(TimeUnit::FromMicroseconds(0),
                    TimeUnit::FromMicroseconds(buffer[lastKeyFrameIndex]->mTime - 1)));
   }
 
   if (mSizeSourceBuffer <= finalSize) {
     return;
@@ -489,17 +490,17 @@ TrackBuffersManager::DoEvictData(const T
       // We've reached a frame that shouldn't be evicted -> Evict after it -> i+1.
       // Or the previous loop reached the eviction threshold -> Evict from it -> i+1.
       evictedFramesStartIndex = i + 1;
       break;
     }
     toEvict -= frame->ComputedSizeOfIncludingThis();
   }
   if (evictedFramesStartIndex < buffer.Length()) {
-    MSE_DEBUG("Step2. Evicting %lld bytes from trailing data",
+    MSE_DEBUG("Step2. Evicting %" PRId64 " bytes from trailing data",
               mSizeSourceBuffer - finalSize - toEvict);
     CodedFrameRemoval(
       TimeInterval(TimeUnit::FromMicroseconds(buffer[evictedFramesStartIndex]->mTime),
                    TimeUnit::FromInfinity()));
   }
 }
 
 RefPtr<TrackBuffersManager::RangeRemovalPromise>
@@ -768,17 +769,17 @@ TrackBuffersManager::NeedMoreData()
   mSourceBufferAttributes = nullptr;
   mCurrentTask = nullptr;
   ProcessTasks();
 }
 
 void
 TrackBuffersManager::RejectAppend(const MediaResult& aRejectValue, const char* aName)
 {
-  MSE_DEBUG("rv=%u", aRejectValue.Code());
+  MSE_DEBUG("rv=%" PRIu32, static_cast<uint32_t>(aRejectValue.Code()));
   MOZ_DIAGNOSTIC_ASSERT(mCurrentTask && mCurrentTask->GetType() == SourceBufferTask::Type::AppendBuffer);
 
   mCurrentTask->As<AppendBufferTask>()->mPromise.Reject(aRejectValue, __func__);
   mSourceBufferAttributes = nullptr;
   mCurrentTask = nullptr;
   ProcessTasks();
 }
 
@@ -1174,18 +1175,19 @@ TrackBuffersManager::CodedFrameProcessin
   return p;
 }
 
 void
 TrackBuffersManager::OnDemuxFailed(TrackType aTrack,
                                    const MediaResult& aError)
 {
   MOZ_ASSERT(OnTaskQueue());
-  MSE_DEBUG("Failed to demux %s, failure:%u",
-            aTrack == TrackType::kVideoTrack ? "video" : "audio", aError.Code());
+  MSE_DEBUG("Failed to demux %s, failure:%" PRIu32,
+            aTrack == TrackType::kVideoTrack ? "video" : "audio",
+            static_cast<uint32_t>(aError.Code()));
   switch (aError.Code()) {
     case NS_ERROR_DOM_MEDIA_END_OF_STREAM:
     case NS_ERROR_DOM_MEDIA_WAITING_FOR_DATA:
       if (aTrack == TrackType::kVideoTrack) {
         DoDemuxAudio();
       } else {
         CompleteCodedFrameProcessing();
       }
@@ -1210,17 +1212,17 @@ TrackBuffersManager::DoDemuxVideo()
            &TrackBuffersManager::OnVideoDemuxFailed)
     ->Track(mVideoTracks.mDemuxRequest);
 }
 
 void
 TrackBuffersManager::OnVideoDemuxCompleted(RefPtr<MediaTrackDemuxer::SamplesHolder> aSamples)
 {
   MOZ_ASSERT(OnTaskQueue());
-  MSE_DEBUG("%d video samples demuxed", aSamples->mSamples.Length());
+  MSE_DEBUG("%" PRIuSIZE " video samples demuxed", aSamples->mSamples.Length());
   mVideoTracks.mDemuxRequest.Complete();
   mVideoTracks.mQueuedSamples.AppendElements(aSamples->mSamples);
   DoDemuxAudio();
 }
 
 void
 TrackBuffersManager::DoDemuxAudio()
 {
@@ -1235,17 +1237,17 @@ TrackBuffersManager::DoDemuxAudio()
            &TrackBuffersManager::OnAudioDemuxFailed)
     ->Track(mAudioTracks.mDemuxRequest);
 }
 
 void
 TrackBuffersManager::OnAudioDemuxCompleted(RefPtr<MediaTrackDemuxer::SamplesHolder> aSamples)
 {
   MOZ_ASSERT(OnTaskQueue());
-  MSE_DEBUG("%d audio samples demuxed", aSamples->mSamples.Length());
+  MSE_DEBUG("%" PRIuSIZE " audio samples demuxed", aSamples->mSamples.Length());
   mAudioTracks.mDemuxRequest.Complete();
   mAudioTracks.mQueuedSamples.AppendElements(aSamples->mSamples);
   CompleteCodedFrameProcessing();
 }
 
 void
 TrackBuffersManager::CompleteCodedFrameProcessing()
 {
@@ -1436,17 +1438,17 @@ TrackBuffersManager::ProcessFrames(Track
   // Highest presentation time seen in samples block.
   TimeUnit highestSampleTime;
 
   if (aSamples.Length()) {
     aTrackData.mLastParsedEndTime = TimeUnit();
   }
 
   for (auto& sample : aSamples) {
-    SAMPLE_DEBUG("Processing %s frame(pts:%lld end:%lld, dts:%lld, duration:%lld, "
+    SAMPLE_DEBUG("Processing %s frame(pts:%" PRId64 " end:%" PRId64 ", dts:%" PRId64 ", duration:%" PRId64 ", "
                "kf:%d)",
                aTrackData.mInfo->mMimeType.get(),
                sample->mTime,
                sample->GetEndTime(),
                sample->mTimecode,
                sample->mDuration,
                sample->mKeyframe);
 
@@ -1664,17 +1666,17 @@ TrackBuffersManager::CheckNextInsertionI
 void
 TrackBuffersManager::InsertFrames(TrackBuffer& aSamples,
                                   const TimeIntervals& aIntervals,
                                   TrackData& aTrackData)
 {
   // 5. Let track buffer equal the track buffer that the coded frame will be added to.
   auto& trackBuffer = aTrackData;
 
-  MSE_DEBUGV("Processing %d %s frames(start:%lld end:%lld)",
+  MSE_DEBUGV("Processing %" PRIuSIZE " %s frames(start:%" PRId64 " end:%" PRId64 ")",
              aSamples.Length(),
              aTrackData.mInfo->mMimeType.get(),
              aIntervals.GetStart().ToMicroseconds(),
              aIntervals.GetEnd().ToMicroseconds());
 
   // TODO: Handle splicing of audio (and text) frames.
   // 11. Let spliced audio frame be an unset variable for holding audio splice information
   // 12. Let spliced timed text frame be an unset variable for holding timed text splice information
@@ -2131,17 +2133,17 @@ TrackBuffersManager::Seek(TrackInfo::Tra
       lastKeyFrameTime = Some(sampleTime);
       lastKeyFrameIndex = i;
     }
     if (sampleTime == aTime ||
         (sampleTime > aTime && lastKeyFrameTime.isSome())) {
       break;
     }
   }
-  MSE_DEBUG("Keyframe %s found at %lld @ %u",
+  MSE_DEBUG("Keyframe %s found at %" PRId64 " @ %u",
             lastKeyFrameTime.isSome() ? "" : "not",
             lastKeyFrameTime.refOr(TimeUnit()).ToMicroseconds(),
             lastKeyFrameIndex);
 
   trackBuffer.mNextGetSampleIndex = Some(lastKeyFrameIndex);
   trackBuffer.mNextSampleTimecode = lastKeyFrameTimecode;
   trackBuffer.mNextSampleTime = lastKeyFrameTime.refOr(TimeUnit());
   ResetEvictionIndex(trackBuffer);
@@ -2346,17 +2348,17 @@ TrackBuffersManager::GetSample(TrackInfo
     trackData.mNextGetSampleIndex = Some(uint32_t(track.Length()));
     aResult = NS_ERROR_DOM_MEDIA_END_OF_STREAM;
     return nullptr;
   }
 
   // Our previous index has been overwritten, attempt to find the new one.
   int32_t pos = FindCurrentPosition(aTrack, aFuzz);
   if (pos < 0) {
-    MSE_DEBUG("Couldn't find sample (pts:%lld dts:%lld)",
+    MSE_DEBUG("Couldn't find sample (pts:%" PRId64 " dts:%" PRId64 ")",
               trackData.mNextSampleTime.ToMicroseconds(),
               trackData.mNextSampleTimecode.ToMicroseconds());
     return nullptr;
   }
 
   const RefPtr<MediaRawData>& sample = track[pos];
   RefPtr<MediaRawData> p = sample->Clone();
   if (!p) {
--- a/dom/media/ogg/OggCodecState.cpp
+++ b/dom/media/ogg/OggCodecState.cpp
@@ -1609,17 +1609,17 @@ SkeletonState::DecodeIndex(ogg_packet* a
       || numKeyPoints < 0) {
     // Packet size is less than the theoretical minimum size, or the packet is
     // claiming to store more keypoints than it's capable of storing. This means
     // that the numKeyPoints field is too large or small for the packet to
     // possibly contain as many packets as it claims to, so the numKeyPoints
     // field is possibly malicious. Don't try decoding this index, we may run
     // out of memory.
     LOG(LogLevel::Debug, ("Possibly malicious number of key points reported "
-                       "(%lld) in index packet for stream %u.",
+                       "(%" PRId64 ") in index packet for stream %u.",
                        numKeyPoints,
                        serialno));
     return (mActive = false);
   }
 
   nsAutoPtr<nsKeyFrameIndex> keyPoints(new nsKeyFrameIndex(startTime, endTime));
 
   p = aPacket->packet + INDEX_KEYPOINT_OFFSET;
@@ -1716,17 +1716,17 @@ SkeletonState::IndexedSeekTarget(int64_t
         && k.mOffset < r.mKeyPoint.mOffset) {
       r.mKeyPoint = k;
       r.mSerial = aTracks[i];
     }
   }
   if (r.IsNull()) {
     return NS_ERROR_FAILURE;
   }
-  LOG(LogLevel::Debug, ("Indexed seek target for time %lld is offset %lld",
+  LOG(LogLevel::Debug, ("Indexed seek target for time %" PRId64 " is offset %" PRId64,
                      aTarget, r.mKeyPoint.mOffset));
   aResult = r;
   return NS_OK;
 }
 
 nsresult
 SkeletonState::GetDuration(const nsTArray<uint32_t>& aTracks,
                            int64_t& aDuration)
@@ -1869,17 +1869,17 @@ SkeletonState::DecodeHeader(OggPacketPtr
         || aPacket->bytes < SKELETON_4_0_MIN_HEADER_LEN) {
       return false;
     }
 
     // Extract the segment length.
     mLength =
       LittleEndian::readInt64(aPacket->packet + SKELETON_FILE_LENGTH_OFFSET);
 
-    LOG(LogLevel::Debug, ("Skeleton segment length: %lld", mLength));
+    LOG(LogLevel::Debug, ("Skeleton segment length: %" PRId64, mLength));
 
     // Initialize the serialno-to-index map.
     return true;
   } else if (IsSkeletonIndex(aPacket.get()) && mVersion >= SKELETON_VERSION(4,0)) {
     return DecodeIndex(aPacket.get());
   } else if (IsSkeletonFisbone(aPacket.get())) {
     return DecodeFisbone(aPacket.get());
   } else if (aPacket->e_o_s) {
--- a/dom/media/ogg/OggDemuxer.cpp
+++ b/dom/media/ogg/OggDemuxer.cpp
@@ -302,25 +302,25 @@ OggDemuxer::Reset(TrackInfo::TrackType a
 bool
 OggDemuxer::ReadHeaders(TrackInfo::TrackType aType,
                         OggCodecState* aState)
 {
   while (!aState->DoneReadingHeaders()) {
     DemuxUntilPacketAvailable(aType, aState);
     OggPacketPtr packet = aState->PacketOut();
     if (!packet) {
-      OGG_DEBUG("Ran out of header packets early; deactivating stream %ld", aState->mSerial);
+      OGG_DEBUG("Ran out of header packets early; deactivating stream %" PRIu32, aState->mSerial);
       aState->Deactivate();
       return false;
     }
 
     // Local OggCodecState needs to decode headers in order to process
     // packet granulepos -> time mappings, etc.
     if (!aState->DecodeHeader(Move(packet))) {
-      OGG_DEBUG("Failed to decode ogg header packet; deactivating stream %ld", aState->mSerial);
+      OGG_DEBUG("Failed to decode ogg header packet; deactivating stream %" PRIu32, aState->mSerial);
       aState->Deactivate();
       return false;
     }
   }
 
   return aState->Init();
 }
 
@@ -359,29 +359,29 @@ void
 OggDemuxer::SetupTargetSkeleton()
 {
   // Setup skeleton related information after mVorbisState & mTheroState
   // being set (if they exist).
   if (mSkeletonState) {
     if (!HasAudio() && !HasVideo()) {
       // We have a skeleton track, but no audio or video, may as well disable
       // the skeleton, we can't do anything useful with this media.
-      OGG_DEBUG("Deactivating skeleton stream %ld", mSkeletonState->mSerial);
+      OGG_DEBUG("Deactivating skeleton stream %" PRIu32, mSkeletonState->mSerial);
       mSkeletonState->Deactivate();
     } else if (ReadHeaders(TrackInfo::kAudioTrack, mSkeletonState) &&
                mSkeletonState->HasIndex()) {
       // We don't particularly care about which track we are currently using
       // as both MediaResource points to the same content.
       // Extract the duration info out of the index, so we don't need to seek to
       // the end of resource to get it.
       nsTArray<uint32_t> tracks;
       BuildSerialList(tracks);
       int64_t duration = 0;
       if (NS_SUCCEEDED(mSkeletonState->GetDuration(tracks, duration))) {
-        OGG_DEBUG("Got duration from Skeleton index %lld", duration);
+        OGG_DEBUG("Got duration from Skeleton index %" PRId64, duration);
         mInfo.mMetadataDuration.emplace(TimeUnit::FromMicroseconds(duration));
       }
     }
   }
 }
 
 void
 OggDemuxer::SetupMediaTracksInfo(const nsTArray<uint32_t>& aSerials)
@@ -546,34 +546,34 @@ OggDemuxer::ReadMetadata()
 
   SetupTargetSkeleton();
   SetupMediaTracksInfo(serials);
 
   if (HasAudio() || HasVideo()) {
     int64_t startTime = -1;
     FindStartTime(startTime);
     if (startTime >= 0) {
-      OGG_DEBUG("Detected stream start time %lld", startTime);
+      OGG_DEBUG("Detected stream start time %" PRId64, startTime);
       mStartTime.emplace(startTime);
     }
 
     if (mInfo.mMetadataDuration.isNothing() &&
         Resource(TrackInfo::kAudioTrack)->GetLength() >= 0) {
       // We didn't get a duration from the index or a Content-Duration header.
       // Seek to the end of file to find the end time.
       int64_t length = Resource(TrackInfo::kAudioTrack)->GetLength();
 
       NS_ASSERTION(length > 0, "Must have a content length to get end time");
 
       int64_t endTime = RangeEndTime(TrackInfo::kAudioTrack, length);
 
       if (endTime != -1) {
         mInfo.mUnadjustedMetadataEndTime.emplace(TimeUnit::FromMicroseconds(endTime));
         mInfo.mMetadataDuration.emplace(TimeUnit::FromMicroseconds(endTime - mStartTime.refOr(0)));
-        OGG_DEBUG("Got Ogg duration from seeking to end %lld", endTime);
+        OGG_DEBUG("Got Ogg duration from seeking to end %" PRId64, endTime);
       }
     }
     if (mInfo.mMetadataDuration.isNothing()) {
       mInfo.mMetadataDuration.emplace(TimeUnit::FromInfinity());
     }
     if (HasAudio()) {
       mInfo.mAudio.mDuration = mInfo.mMetadataDuration->ToMicroseconds();
     }
@@ -996,25 +996,25 @@ OggDemuxer::FindStartTime(int64_t& aOutS
   // Extract the start times of the bitstreams in order to calculate
   // the duration.
   int64_t videoStartTime = INT64_MAX;
   int64_t audioStartTime = INT64_MAX;
 
   if (HasVideo()) {
     FindStartTime(TrackInfo::kVideoTrack, videoStartTime);
     if (videoStartTime != INT64_MAX) {
-      OGG_DEBUG("OggDemuxer::FindStartTime() video=%lld", videoStartTime);
+      OGG_DEBUG("OggDemuxer::FindStartTime() video=%" PRId64, videoStartTime);
       mVideoOggState.mStartTime =
         Some(TimeUnit::FromMicroseconds(videoStartTime));
     }
   }
   if (HasAudio()) {
     FindStartTime(TrackInfo::kAudioTrack, audioStartTime);
     if (audioStartTime != INT64_MAX) {
-      OGG_DEBUG("OggDemuxer::FindStartTime() audio=%lld", audioStartTime);
+      OGG_DEBUG("OggDemuxer::FindStartTime() audio=%" PRId64, audioStartTime);
       mAudioOggState.mStartTime =
         Some(TimeUnit::FromMicroseconds(audioStartTime));
     }
   }
 
   int64_t startTime = std::min(videoStartTime, audioStartTime);
   if (startTime != INT64_MAX) {
     aOutStartTime = startTime;
@@ -1036,17 +1036,17 @@ OggDemuxer::FindStartTime(TrackInfo::Tra
     aOutStartTime = startTime;
   }
 }
 
 nsresult
 OggDemuxer::SeekInternal(TrackInfo::TrackType aType, const TimeUnit& aTarget)
 {
   int64_t target = aTarget.ToMicroseconds();
-  OGG_DEBUG("About to seek to %lld", target);
+  OGG_DEBUG("About to seek to %" PRId64, target);
   nsresult res;
   int64_t adjustedTarget = target;
   int64_t startTime = StartTime(aType);
   int64_t endTime = mInfo.mMetadataDuration->ToMicroseconds();
   if (aType == TrackInfo::kAudioTrack && mOpusState){
     adjustedTarget = std::max(startTime, target - OGG_SEEK_OPUS_PREROLL);
   }
 
@@ -1107,17 +1107,17 @@ OggDemuxer::SeekInternal(TrackInfo::Trac
       OGG_DEBUG("End of stream reached before keyframe found in indexed seek");
       break;
     }
     int64_t startTstamp = state->PacketStartTime(packet);
     if (foundKeyframe && startTstamp > adjustedTarget) {
       break;
     }
     if (state->IsKeyframe(packet)) {
-      OGG_DEBUG("keyframe found after seeking at %lld", startTstamp);
+      OGG_DEBUG("keyframe found after seeking at %" PRId64, startTstamp);
       tempPackets.Erase();
       foundKeyframe = true;
     }
     if (foundKeyframe && startTstamp == adjustedTarget) {
       break;
     }
     if (foundKeyframe) {
       tempPackets.Append(state->PacketOut());
@@ -1164,17 +1164,17 @@ OggDemuxer::SeekToKeyframeUsingIndex(Tra
   int64_t tell = Resource(aType)->Tell();
 
   // Seek to the keypoint returned by the index.
   if (keyframe.mKeyPoint.mOffset > Resource(aType)->GetLength() ||
       keyframe.mKeyPoint.mOffset < 0) {
     // Index must be invalid.
     return RollbackIndexedSeek(aType, tell);
   }
-  LOG(LogLevel::Debug, ("Seeking using index to keyframe at offset %lld\n",
+  LOG(LogLevel::Debug, ("Seeking using index to keyframe at offset %" PRId64 "\n",
                      keyframe.mKeyPoint.mOffset));
   nsresult res = Resource(aType)->Seek(nsISeekableStream::NS_SEEK_SET,
                                        keyframe.mKeyPoint.mOffset);
   NS_ENSURE_SUCCESS(res, SEEK_FATAL_ERROR);
 
   // We've moved the read set, so reset decode.
   res = Reset(aType);
   NS_ENSURE_SUCCESS(res, SEEK_FATAL_ERROR);
@@ -1307,17 +1307,17 @@ OggTrackDemuxer::Seek(const TimeUnit& aT
   mQueuedSample = nullptr;
   TimeUnit seekTime = aTime;
   if (mParent->SeekInternal(mType, aTime) == NS_OK) {
     RefPtr<MediaRawData> sample(NextSample());
 
     // Check what time we actually seeked to.
     if (sample != nullptr) {
       seekTime = TimeUnit::FromMicroseconds(sample->mTime);
-      OGG_DEBUG("%p seeked to time %lld", this, seekTime.ToMicroseconds());
+      OGG_DEBUG("%p seeked to time %" PRId64, this, seekTime.ToMicroseconds());
     }
     mQueuedSample = sample;
 
     return SeekPromise::CreateAndResolve(seekTime, __func__);
   } else {
     return SeekPromise::CreateAndReject(NS_ERROR_DOM_MEDIA_DEMUXER_ERR, __func__);
   }
 }
@@ -1676,17 +1676,17 @@ nsresult
 OggDemuxer::SeekInBufferedRange(TrackInfo::TrackType aType,
                                 int64_t aTarget,
                                 int64_t aAdjustedTarget,
                                 int64_t aStartTime,
                                 int64_t aEndTime,
                                 const nsTArray<SeekRange>& aRanges,
                                 const SeekRange& aRange)
 {
-  OGG_DEBUG("Seeking in buffered data to %lld using bisection search", aTarget);
+  OGG_DEBUG("Seeking in buffered data to %" PRId64 " using bisection search", aTarget);
   if (aType == TrackInfo::kVideoTrack || aAdjustedTarget >= aTarget) {
     // We know the exact byte range in which the target must lie. It must
     // be buffered in the media cache. Seek there.
     nsresult res = SeekBisection(aType, aTarget, aRange, 0);
     if (NS_FAILED(res) || aType != TrackInfo::kVideoTrack) {
       return res;
     }
 
@@ -1723,17 +1723,17 @@ OggDemuxer::SeekInBufferedRange(TrackInf
 
 nsresult
 OggDemuxer::SeekInUnbuffered(TrackInfo::TrackType aType,
                              int64_t aTarget,
                              int64_t aStartTime,
                              int64_t aEndTime,
                              const nsTArray<SeekRange>& aRanges)
 {
-  OGG_DEBUG("Seeking in unbuffered data to %lld using bisection search", aTarget);
+  OGG_DEBUG("Seeking in unbuffered data to %" PRId64 " using bisection search", aTarget);
 
   // If we've got an active Theora bitstream, determine the maximum possible
   // time in usecs which a keyframe could be before a given interframe. We
   // subtract this from our seek target, seek to the new target, and then
   // will decode forward to the original seek target. We should encounter a
   // keyframe in that interval. This prevents us from needing to run two
   // bisections; one for the seek target frame, and another to find its
   // keyframe. It's usually faster to just download this extra data, rather
--- a/dom/media/platforms/agnostic/AgnosticDecoderModule.cpp
+++ b/dom/media/platforms/agnostic/AgnosticDecoderModule.cpp
@@ -1,34 +1,35 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim:set ts=2 sw=2 sts=2 et cindent: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "AgnosticDecoderModule.h"
-#include "mozilla/Logging.h"
 #include "OpusDecoder.h"
+#include "TheoraDecoder.h"
+#include "VPXDecoder.h"
 #include "VorbisDecoder.h"
-#include "VPXDecoder.h"
 #include "WAVDecoder.h"
-#include "TheoraDecoder.h"
+#include "mozilla/Logging.h"
 
 namespace mozilla {
 
 bool
-AgnosticDecoderModule::SupportsMimeType(const nsACString& aMimeType,
-                                        DecoderDoctorDiagnostics* aDiagnostics) const
+AgnosticDecoderModule::SupportsMimeType(
+  const nsACString& aMimeType,
+  DecoderDoctorDiagnostics* aDiagnostics) const
 {
   bool supports =
-    VPXDecoder::IsVPX(aMimeType) ||
-    OpusDataDecoder::IsOpus(aMimeType) ||
-    VorbisDataDecoder::IsVorbis(aMimeType) ||
-    WaveDataDecoder::IsWave(aMimeType) ||
-    TheoraDecoder::IsTheora(aMimeType);
+    VPXDecoder::IsVPX(aMimeType)
+    || OpusDataDecoder::IsOpus(aMimeType)
+    || VorbisDataDecoder::IsVorbis(aMimeType)
+    || WaveDataDecoder::IsWave(aMimeType)
+    || TheoraDecoder::IsTheora(aMimeType);
   MOZ_LOG(sPDMLog, LogLevel::Debug, ("Agnostic decoder %s requested type",
         supports ? "supports" : "rejects"));
   return supports;
 }
 
 already_AddRefed<MediaDataDecoder>
 AgnosticDecoderModule::CreateVideoDecoder(const CreateDecoderParams& aParams)
 {
--- a/dom/media/platforms/agnostic/AgnosticDecoderModule.h
+++ b/dom/media/platforms/agnostic/AgnosticDecoderModule.h
@@ -1,30 +1,31 @@
 #if !defined(AgnosticDecoderModule_h_)
 #define AgnosticDecoderModule_h_
 
 #include "PlatformDecoderModule.h"
 
 namespace mozilla {
 
-class AgnosticDecoderModule : public PlatformDecoderModule {
+class AgnosticDecoderModule : public PlatformDecoderModule
+{
 public:
   AgnosticDecoderModule() = default;
-  virtual ~AgnosticDecoderModule() = default;
 
   bool SupportsMimeType(const nsACString& aMimeType,
                         DecoderDoctorDiagnostics* aDiagnostics) const override;
 
   ConversionRequired
   DecoderNeedsConversion(const TrackInfo& aConfig) const override
   {
     return ConversionRequired::kNeedNone;
   }
 
 protected:
+  virtual ~AgnosticDecoderModule() = default;
   // Decode thread.
   already_AddRefed<MediaDataDecoder>
   CreateVideoDecoder(const CreateDecoderParams& aParams) override;
 
   // Decode thread.
   already_AddRefed<MediaDataDecoder>
   CreateAudioDecoder(const CreateDecoderParams& aParams) override;
 };
--- a/dom/media/platforms/agnostic/BlankDecoderModule.cpp
+++ b/dom/media/platforms/agnostic/BlankDecoderModule.cpp
@@ -1,53 +1,56 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim:set ts=2 sw=2 sts=2 et cindent: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "ImageContainer.h"
+#include "MP4Decoder.h"
 #include "MediaDecoderReader.h"
 #include "MediaInfo.h"
-#include "mozilla/CheckedInt.h"
-#include "mozilla/mozalloc.h" // for operator new, and new (fallible)
-#include "mozilla/RefPtr.h"
-#include "mozilla/TaskQueue.h"
-#include "mp4_demuxer/AnnexB.h"
-#include "mp4_demuxer/H264.h"
-#include "MP4Decoder.h"
-#include "nsAutoPtr.h"
-#include "nsRect.h"
 #include "PlatformDecoderModule.h"
 #include "ReorderQueue.h"
 #include "TimeUnits.h"
 #include "VideoUtils.h"
+#include "mozilla/CheckedInt.h"
+#include "mozilla/RefPtr.h"
+#include "mozilla/TaskQueue.h"
+#include "mozilla/mozalloc.h" // for operator new, and new (fallible)
+#include "mp4_demuxer/AnnexB.h"
+#include "mp4_demuxer/H264.h"
+#include "nsAutoPtr.h"
+#include "nsRect.h"
 
 namespace mozilla {
 
 // Decoder that uses a passed in object's Create function to create blank
 // MediaData objects.
 template<class BlankMediaDataCreator>
-class BlankMediaDataDecoder : public MediaDataDecoder {
+class BlankMediaDataDecoder : public MediaDataDecoder
+{
 public:
-
   BlankMediaDataDecoder(BlankMediaDataCreator* aCreator,
                         const CreateDecoderParams& aParams)
     : mCreator(aCreator)
-    , mMaxRefFrames(aParams.mConfig.GetType() == TrackInfo::kVideoTrack &&
-                    MP4Decoder::IsH264(aParams.mConfig.mMimeType)
-                    ? mp4_demuxer::AnnexB::HasSPS(aParams.VideoConfig().mExtraData)
-                      ? mp4_demuxer::H264::ComputeMaxRefFrames(aParams.VideoConfig().mExtraData)
-                      : 16
-                    : 0)
+    , mMaxRefFrames(
+        aParams.mConfig.GetType() == TrackInfo::kVideoTrack
+        && MP4Decoder::IsH264(aParams.mConfig.mMimeType)
+           ? mp4_demuxer::AnnexB::HasSPS(aParams.VideoConfig().mExtraData)
+             ? mp4_demuxer::H264::ComputeMaxRefFrames(
+                 aParams.VideoConfig().mExtraData)
+             : 16
+           : 0)
     , mType(aParams.mConfig.GetType())
   {
   }
 
-  RefPtr<InitPromise> Init() override {
+  RefPtr<InitPromise> Init() override
+  {
     return InitPromise::CreateAndResolve(mType, __func__);
   }
 
   RefPtr<ShutdownPromise> Shutdown() override
   {
     return ShutdownPromise::CreateAndResolve(true, __func__);
   }
 
@@ -94,31 +97,33 @@ public:
 
 private:
   nsAutoPtr<BlankMediaDataCreator> mCreator;
   const uint32_t mMaxRefFrames;
   ReorderQueue mReorderQueue;
   TrackInfo::TrackType mType;
 };
 
-class BlankVideoDataCreator {
+class BlankVideoDataCreator
+{
 public:
   BlankVideoDataCreator(uint32_t aFrameWidth,
                         uint32_t aFrameHeight,
                         layers::ImageContainer* aImageContainer)
     : mFrameWidth(aFrameWidth)
     , mFrameHeight(aFrameHeight)
     , mImageContainer(aImageContainer)
   {
     mInfo.mDisplay = nsIntSize(mFrameWidth, mFrameHeight);
     mPicture = gfx::IntRect(0, 0, mFrameWidth, mFrameHeight);
   }
 
-  already_AddRefed<MediaData>
-  Create(const media::TimeUnit& aDTS, const media::TimeUnit& aDuration, int64_t aOffsetInStream)
+  already_AddRefed<MediaData> Create(const media::TimeUnit& aDTS,
+                                     const media::TimeUnit& aDuration,
+                                     int64_t aOffsetInStream)
   {
     // Create a fake YUV buffer in a 420 format. That is, an 8bpp Y plane,
     // with a U and V plane that are half the size of the Y plane, i.e 8 bit,
     // 2x2 subsampled.
     const int sizeY = mFrameWidth * mFrameHeight;
     const int sizeCbCr = ((mFrameWidth + 1) / 2) * ((mFrameHeight + 1) / 2);
     auto frame = MakeUnique<uint8_t[]>(sizeY + sizeCbCr);
     VideoData::YCbCrBuffer buffer;
@@ -165,35 +170,36 @@ public:
 private:
   VideoInfo mInfo;
   gfx::IntRect mPicture;
   uint32_t mFrameWidth;
   uint32_t mFrameHeight;
   RefPtr<layers::ImageContainer> mImageContainer;
 };
 
-class BlankAudioDataCreator {
+class BlankAudioDataCreator
+{
 public:
   BlankAudioDataCreator(uint32_t aChannelCount, uint32_t aSampleRate)
     : mFrameSum(0), mChannelCount(aChannelCount), mSampleRate(aSampleRate)
   {
   }
 
   MediaData* Create(const media::TimeUnit& aDTS,
                     const media::TimeUnit& aDuration,
                     int64_t aOffsetInStream)
   {
     // Convert duration to frames. We add 1 to duration to account for
     // rounding errors, so we get a consistent tone.
     CheckedInt64 frames =
       UsecsToFrames(aDuration.ToMicroseconds()+1, mSampleRate);
-    if (!frames.isValid() ||
-        !mChannelCount ||
-        !mSampleRate ||
-        frames.value() > (UINT32_MAX / mChannelCount)) {
+    if (!frames.isValid()
+        || !mChannelCount
+        || !mSampleRate
+        || frames.value() > (UINT32_MAX / mChannelCount)) {
       return nullptr;
     }
     AlignedAudioBuffer samples(frames.value() * mChannelCount);
     if (!samples) {
       return nullptr;
     }
     // Fill the sound buffer with an A4 tone.
     static const float pi = 3.14159265f;
@@ -215,45 +221,47 @@ public:
   }
 
 private:
   int64_t mFrameSum;
   uint32_t mChannelCount;
   uint32_t mSampleRate;
 };
 
-class BlankDecoderModule : public PlatformDecoderModule {
+class BlankDecoderModule : public PlatformDecoderModule
+{
 public:
 
   // Decode thread.
   already_AddRefed<MediaDataDecoder>
-  CreateVideoDecoder(const CreateDecoderParams& aParams) override {
+  CreateVideoDecoder(const CreateDecoderParams& aParams) override
+  {
     const VideoInfo& config = aParams.VideoConfig();
     BlankVideoDataCreator* creator = new BlankVideoDataCreator(
       config.mDisplay.width, config.mDisplay.height, aParams.mImageContainer);
     RefPtr<MediaDataDecoder> decoder =
       new BlankMediaDataDecoder<BlankVideoDataCreator>(creator, aParams);
     return decoder.forget();
   }
 
   // Decode thread.
   already_AddRefed<MediaDataDecoder>
-  CreateAudioDecoder(const CreateDecoderParams& aParams) override {
+  CreateAudioDecoder(const CreateDecoderParams& aParams) override
+  {
     const AudioInfo& config = aParams.AudioConfig();
     BlankAudioDataCreator* creator = new BlankAudioDataCreator(
       config.mChannels, config.mRate);
 
     RefPtr<MediaDataDecoder> decoder =
       new BlankMediaDataDecoder<BlankAudioDataCreator>(creator, aParams);
     return decoder.forget();
   }
 
-  bool
-  SupportsMimeType(const nsACString& aMimeType,
-                   DecoderDoctorDiagnostics* aDiagnostics) const override
+  bool SupportsMimeType(const nsACString& aMimeType,
+                        DecoderDoctorDiagnostics* aDiagnostics) const override
   {
     return true;
   }
 
   ConversionRequired
   DecoderNeedsConversion(const TrackInfo& aConfig) const override
   {
     if (aConfig.IsVideo() && MP4Decoder::IsH264(aConfig.mMimeType)) {
--- a/dom/media/platforms/agnostic/OpusDecoder.cpp
+++ b/dom/media/platforms/agnostic/OpusDecoder.cpp
@@ -7,16 +7,17 @@
 #include "OpusDecoder.h"
 #include "OpusParser.h"
 #include "TimeUnits.h"
 #include "VorbisUtils.h"
 #include "VorbisDecoder.h" // For VorbisLayout
 #include "mozilla/EndianUtils.h"
 #include "mozilla/PodOperations.h"
 #include "mozilla/SyncRunnable.h"
+#include "mozilla/SizePrintfMacros.h"
 
 #include <inttypes.h>  // For PRId64
 
 #include "opus/opus.h"
 extern "C" {
 #include "opus/opus_multistream.h"
 }
 
@@ -171,17 +172,17 @@ OpusDataDecoder::ProcessDecode(MediaRawD
     mFrames = 0;
     mLastFrameTime = Some(aSample->mTime);
   }
 
   // Maximum value is 63*2880, so there's no chance of overflow.
   uint32_t frames_number = opus_packet_get_nb_frames(aSample->Data(),
                                                     aSample->Size());
   if (frames_number <= 0) {
-    OPUS_DEBUG("Invalid packet header: r=%ld length=%ld", frames_number,
+    OPUS_DEBUG("Invalid packet header: r=%" PRIu32 " length=%" PRIuSIZE, frames_number,
                aSample->Size());
     return DecodePromise::CreateAndReject(
       MediaResult(NS_ERROR_DOM_MEDIA_DECODE_ERR,
                   RESULT_DETAIL("Invalid packet header: r=%d length=%u",
                                 frames_number, uint32_t(aSample->Size()))),
       __func__);
   }
 
--- a/dom/media/platforms/agnostic/TheoraDecoder.cpp
+++ b/dom/media/platforms/agnostic/TheoraDecoder.cpp
@@ -1,20 +1,20 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim:set ts=2 sw=2 sts=2 et cindent: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "TheoraDecoder.h"
+#include "TimeUnits.h"
 #include "XiphExtradata.h"
 #include "gfx2DGlue.h"
+#include "mozilla/PodOperations.h"
 #include "nsError.h"
-#include "TimeUnits.h"
-#include "mozilla/PodOperations.h"
 
 #include <algorithm>
 
 #undef LOG
 #define LOG(arg, ...) MOZ_LOG(gMediaDecoderLog, mozilla::LogLevel::Debug, ("TheoraDecoder(%p)::%s: " arg, this, __func__, ##__VA_ARGS__))
 
 namespace mozilla {
 
@@ -75,21 +75,22 @@ TheoraDecoder::Init()
   th_comment_init(&mTheoraComment);
   th_info_init(&mTheoraInfo);
 
   nsTArray<unsigned char*> headers;
   nsTArray<size_t> headerLens;
   if (!XiphExtradataToHeaders(headers, headerLens,
       mInfo.mCodecSpecificConfig->Elements(),
       mInfo.mCodecSpecificConfig->Length())) {
-      return InitPromise::CreateAndReject(NS_ERROR_DOM_MEDIA_FATAL_ERR, __func__);
+    return InitPromise::CreateAndReject(NS_ERROR_DOM_MEDIA_FATAL_ERR, __func__);
   }
   for (size_t i = 0; i < headers.Length(); i++) {
     if (NS_FAILED(DoDecodeHeader(headers[i], headerLens[i]))) {
-      return InitPromise::CreateAndReject(NS_ERROR_DOM_MEDIA_FATAL_ERR, __func__);
+      return InitPromise::CreateAndReject(NS_ERROR_DOM_MEDIA_FATAL_ERR,
+                                          __func__);
     }
   }
   if (mPacketCount != 3) {
     return InitPromise::CreateAndReject(NS_ERROR_DOM_MEDIA_FATAL_ERR, __func__);
   }
 
   mTheoraDecoderContext = th_decode_alloc(&mTheoraInfo, mTheoraSetupInfo);
   if (mTheoraDecoderContext) {
@@ -107,17 +108,18 @@ TheoraDecoder::Flush()
     return FlushPromise::CreateAndResolve(true, __func__);
   });
 }
 
 nsresult
 TheoraDecoder::DoDecodeHeader(const unsigned char* aData, size_t aLength)
 {
   bool bos = mPacketCount == 0;
-  ogg_packet pkt = InitTheoraPacket(aData, aLength, bos, false, 0, mPacketCount++);
+  ogg_packet pkt =
+    InitTheoraPacket(aData, aLength, bos, false, 0, mPacketCount++);
 
   int r = th_decode_headerin(&mTheoraInfo,
                              &mTheoraComment,
                              &mTheoraSetupInfo,
                              &pkt);
   return r > 0 ? NS_OK : NS_ERROR_FAILURE;
 }
 
@@ -125,17 +127,18 @@ RefPtr<MediaDataDecoder::DecodePromise>
 TheoraDecoder::ProcessDecode(MediaRawData* aSample)
 {
   MOZ_ASSERT(mTaskQueue->IsCurrentThreadIn());
 
   const unsigned char* aData = aSample->Data();
   size_t aLength = aSample->Size();
 
   bool bos = mPacketCount == 0;
-  ogg_packet pkt = InitTheoraPacket(aData, aLength, bos, false, aSample->mTimecode, mPacketCount++);
+  ogg_packet pkt = InitTheoraPacket(
+    aData, aLength, bos, false, aSample->mTimecode, mPacketCount++);
 
   int ret = th_decode_packetin(mTheoraDecoderContext, &pkt, nullptr);
   if (ret == 0 || ret == TH_DUPFRAME) {
     th_ycbcr_buffer ycbcr;
     th_decode_ycbcr_out(mTheoraDecoderContext, ycbcr);
 
     int hdec = !(mTheoraInfo.pixel_fmt & 1);
     int vdec = !(mTheoraInfo.pixel_fmt & 2);
@@ -171,19 +174,24 @@ TheoraDecoder::ProcessDecode(MediaRawDat
                                    aSample->mTime,
                                    aSample->mDuration,
                                    b,
                                    aSample->mKeyframe,
                                    aSample->mTimecode,
                                    mInfo.ScaledImageRect(mTheoraInfo.frame_width,
                                                          mTheoraInfo.frame_height));
     if (!v) {
-      LOG("Image allocation error source %ldx%ld display %ldx%ld picture %ldx%ld",
-          mTheoraInfo.frame_width, mTheoraInfo.frame_height, mInfo.mDisplay.width, mInfo.mDisplay.height,
-          mInfo.mImage.width, mInfo.mImage.height);
+      LOG(
+        "Image allocation error source %ux%u display %ux%u picture %ux%u",
+        mTheoraInfo.frame_width,
+        mTheoraInfo.frame_height,
+        mInfo.mDisplay.width,
+        mInfo.mDisplay.height,
+        mInfo.mImage.width,
+        mInfo.mImage.height);
       return DecodePromise::CreateAndReject(
         MediaResult(NS_ERROR_OUT_OF_MEMORY,
                     RESULT_DETAIL("Insufficient memory")),
         __func__);
     }
     return DecodePromise::CreateAndResolve(DecodedData{v}, __func__);
   }
   LOG("Theora Decode error: %d", ret);
--- a/dom/media/platforms/agnostic/TheoraDecoder.h
+++ b/dom/media/platforms/agnostic/TheoraDecoder.h
@@ -2,52 +2,48 @@
 /* vim:set ts=2 sw=2 sts=2 et cindent: */
 /* 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/. */
 #if !defined(TheoraDecoder_h_)
 #define TheoraDecoder_h_
 
 #include "PlatformDecoderModule.h"
-
-#include <stdint.h>
 #include "ogg/ogg.h"
 #include "theora/theoradec.h"
+#include <stdint.h>
 
 namespace mozilla {
 
-  using namespace layers;
-
 class TheoraDecoder : public MediaDataDecoder
 {
 public:
   explicit TheoraDecoder(const CreateDecoderParams& aParams);
 
-  ~TheoraDecoder();
-
   RefPtr<InitPromise> Init() override;
   RefPtr<DecodePromise> Decode(MediaRawData* aSample) override;
   RefPtr<DecodePromise> Drain() override;
   RefPtr<FlushPromise> Flush() override;
   RefPtr<ShutdownPromise> Shutdown() override;
 
   // Return true if mimetype is a Theora codec
   static bool IsTheora(const nsACString& aMimeType);
 
   const char* GetDescriptionName() const override
   {
     return "theora video decoder";
   }
 
 private:
+  ~TheoraDecoder();
   nsresult DoDecodeHeader(const unsigned char* aData, size_t aLength);
 
   RefPtr<DecodePromise> ProcessDecode(MediaRawData* aSample);
 
-  RefPtr<ImageContainer> mImageContainer;
+  RefPtr<layers::ImageContainer> mImageContainer;
   RefPtr<TaskQueue> mTaskQueue;
 
   // Theora header & decoder state
   th_info mTheoraInfo;
   th_comment mTheoraComment;
   th_setup_info *mTheoraSetupInfo;
   th_dec_ctx *mTheoraDecoderContext;
   int mPacketCount;
--- a/dom/media/platforms/agnostic/VPXDecoder.cpp
+++ b/dom/media/platforms/agnostic/VPXDecoder.cpp
@@ -1,20 +1,20 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim:set ts=2 sw=2 sts=2 et cindent: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "VPXDecoder.h"
+#include "TimeUnits.h"
 #include "gfx2DGlue.h"
-#include "nsError.h"
-#include "TimeUnits.h"
 #include "mozilla/PodOperations.h"
 #include "mozilla/SyncRunnable.h"
+#include "nsError.h"
 #include "prsystem.h"
 
 #include <algorithm>
 
 #undef LOG
 #define LOG(arg, ...) MOZ_LOG(sPDMLog, mozilla::LogLevel::Debug, ("VPXDecoder(%p)::%s: " arg, this, __func__, ##__VA_ARGS__))
 
 namespace mozilla {
@@ -232,17 +232,17 @@ VPXDecoder::ProcessDecode(MediaRawData* 
                                        aSample->mTimecode,
                                        mInfo.ScaledImageRect(img->d_w,
                                                              img->d_h));
 
     }
 
     if (!v) {
       LOG(
-        "Image allocation error source %ldx%ld display %ldx%ld picture %ldx%ld",
+        "Image allocation error source %ux%u display %ux%u picture %ux%u",
         img->d_w, img->d_h, mInfo.mDisplay.width, mInfo.mDisplay.height,
         mInfo.mImage.width, mInfo.mImage.height);
       return DecodePromise::CreateAndReject(
         MediaResult(NS_ERROR_OUT_OF_MEMORY, __func__), __func__);
     }
     results.AppendElement(Move(v));
   }
   return DecodePromise::CreateAndResolve(Move(results), __func__);
@@ -287,22 +287,22 @@ VPXDecoder::DecodeAlpha(vpx_image_t** aI
 
   return NS_OK;
 }
 
 /* static */
 bool
 VPXDecoder::IsVPX(const nsACString& aMimeType, uint8_t aCodecMask)
 {
-  return ((aCodecMask & VPXDecoder::VP8) &&
-          aMimeType.EqualsLiteral("video/webm; codecs=vp8")) ||
-         ((aCodecMask & VPXDecoder::VP9) &&
-          aMimeType.EqualsLiteral("video/webm; codecs=vp9")) ||
-         ((aCodecMask & VPXDecoder::VP9) &&
-          aMimeType.EqualsLiteral("video/vp9"));
+  return ((aCodecMask & VPXDecoder::VP8)
+          && aMimeType.EqualsLiteral("video/webm; codecs=vp8"))
+         || ((aCodecMask & VPXDecoder::VP9)
+             && aMimeType.EqualsLiteral("video/webm; codecs=vp9"))
+         || ((aCodecMask & VPXDecoder::VP9)
+             && aMimeType.EqualsLiteral("video/vp9"));
 }
 
 /* static */
 bool
 VPXDecoder::IsVP8(const nsACString& aMimeType)
 {
   return IsVPX(aMimeType, VPXDecoder::VP8);
 }
--- a/dom/media/platforms/agnostic/VPXDecoder.h
+++ b/dom/media/platforms/agnostic/VPXDecoder.h
@@ -11,23 +11,20 @@
 #include <stdint.h>
 #define VPX_DONT_DEFINE_STDINT_TYPES
 #include "vpx/vp8dx.h"
 #include "vpx/vpx_codec.h"
 #include "vpx/vpx_decoder.h"
 
 namespace mozilla {
 
-using namespace layers;
-
 class VPXDecoder : public MediaDataDecoder
 {
 public:
   explicit VPXDecoder(const CreateDecoderParams& aParams);
-  ~VPXDecoder();
 
   RefPtr<InitPromise> Init() override;
   RefPtr<DecodePromise> Decode(MediaRawData* aSample) override;
   RefPtr<DecodePromise> Drain() override;
   RefPtr<FlushPromise> Flush() override;
   RefPtr<ShutdownPromise> Shutdown() override;
   const char* GetDescriptionName() const override
   {
@@ -43,20 +40,21 @@ public:
   // Return true if aMimeType is a one of the strings used by our demuxers to
   // identify VPX of the specified type. Does not parse general content type
   // strings, i.e. white space matters.
   static bool IsVPX(const nsACString& aMimeType, uint8_t aCodecMask=VP8|VP9);
   static bool IsVP8(const nsACString& aMimeType);
   static bool IsVP9(const nsACString& aMimeType);
 
 private:
+  ~VPXDecoder();
   RefPtr<DecodePromise> ProcessDecode(MediaRawData* aSample);
   MediaResult DecodeAlpha(vpx_image_t** aImgAlpha, const MediaRawData* aSample);
 
-  const RefPtr<ImageContainer> mImageContainer;
+  const RefPtr<layers::ImageContainer> mImageContainer;
   const RefPtr<TaskQueue> mTaskQueue;
 
   // VPx decoder state
   vpx_codec_ctx_t mVPX;
 
   // VPx alpha decoder state
   vpx_codec_ctx_t mVPXAlpha;
 
--- a/dom/media/platforms/agnostic/VorbisDecoder.cpp
+++ b/dom/media/platforms/agnostic/VorbisDecoder.cpp
@@ -73,17 +73,18 @@ VorbisDataDecoder::Init()
   AutoTArray<size_t,4> headerLens;
   if (!XiphExtradataToHeaders(headers, headerLens,
                               mInfo.mCodecSpecificConfig->Elements(),
                               mInfo.mCodecSpecificConfig->Length())) {
     return InitPromise::CreateAndReject(NS_ERROR_DOM_MEDIA_FATAL_ERR, __func__);
   }
   for (size_t i = 0; i < headers.Length(); i++) {
     if (NS_FAILED(DecodeHeader(headers[i], headerLens[i]))) {
-      return InitPromise::CreateAndReject(NS_ERROR_DOM_MEDIA_FATAL_ERR, __func__);
+      return InitPromise::CreateAndReject(NS_ERROR_DOM_MEDIA_FATAL_ERR,
+                                          __func__);
     }
   }
 
   MOZ_ASSERT(mPacketCount == 3);
 
   int r = vorbis_synthesis_init(&mVorbisDsp, &mVorbisInfo);
   if (r) {
     return InitPromise::CreateAndReject(NS_ERROR_DOM_MEDIA_FATAL_ERR, __func__);
@@ -110,17 +111,18 @@ VorbisDataDecoder::Init()
 
   return InitPromise::CreateAndResolve(TrackInfo::kAudioTrack, __func__);
 }
 
 nsresult
 VorbisDataDecoder::DecodeHeader(const unsigned char* aData, size_t aLength)
 {
   bool bos = mPacketCount == 0;
-  ogg_packet pkt = InitVorbisPacket(aData, aLength, bos, false, 0, mPacketCount++);
+  ogg_packet pkt =
+    InitVorbisPacket(aData, aLength, bos, false, 0, mPacketCount++);
   MOZ_ASSERT(mPacketCount <= 3);
 
   int r = vorbis_synthesis_headerin(&mVorbisInfo,
                                     &mVorbisComment,
                                     &pkt);
   return r == 0 ? NS_OK : NS_ERROR_FAILURE;
 }
 
@@ -211,18 +213,18 @@ VorbisDataDecoder::ProcessDecode(MediaRa
       return DecodePromise::CreateAndReject(
         MediaResult(
           NS_ERROR_DOM_MEDIA_OVERFLOW_ERR,
           RESULT_DETAIL("Overflow adding total_duration and aTstampUsecs")),
         __func__);
     };
 
     if (!mAudioConverter) {
-      AudioConfig in(AudioConfig::ChannelLayout(channels, VorbisLayout(channels)),
-                     rate);
+      AudioConfig in(
+        AudioConfig::ChannelLayout(channels, VorbisLayout(channels)), rate);
       AudioConfig out(channels, rate);
       if (!in.IsValid() || !out.IsValid()) {
         return DecodePromise::CreateAndReject(
           MediaResult(NS_ERROR_DOM_MEDIA_FATAL_ERR,
                       RESULT_DETAIL("Invalid channel layout:%u", channels)),
           __func__);
       }
       mAudioConverter = MakeUnique<AudioConverter>(in, out);
--- a/dom/media/platforms/agnostic/VorbisDecoder.h
+++ b/dom/media/platforms/agnostic/VorbisDecoder.h
@@ -1,19 +1,19 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim:set ts=2 sw=2 sts=2 et cindent: */
 /* 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/. */
 #if !defined(VorbisDecoder_h_)
 #define VorbisDecoder_h_
 
+#include "AudioConverter.h"
 #include "PlatformDecoderModule.h"
 #include "mozilla/Maybe.h"
-#include "AudioConverter.h"
 
 #ifdef MOZ_TREMOR
 #include "tremor/ivorbiscodec.h"
 #else
 #include "vorbis/codec.h"
 #endif
 
 namespace mozilla {
--- a/dom/media/platforms/agnostic/WAVDecoder.cpp
+++ b/dom/media/platforms/agnostic/WAVDecoder.cpp
@@ -1,16 +1,16 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim:set ts=2 sw=2 sts=2 et cindent: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+#include "AudioSampleFormat.h"
 #include "WAVDecoder.h"
-#include "AudioSampleFormat.h"
 #include "mozilla/SyncRunnable.h"
 
 using mp4_demuxer::ByteReader;
 
 namespace mozilla {
 
 int16_t
 DecodeALawSample(uint8_t aValue)
--- a/dom/media/platforms/agnostic/eme/EMEDecoderModule.cpp
+++ b/dom/media/platforms/agnostic/eme/EMEDecoderModule.cpp
@@ -1,28 +1,30 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim:set ts=2 sw=2 sts=2 et cindent: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "EMEDecoderModule.h"
 #include "EMEVideoDecoder.h"
-#include "MediaDataDecoderProxy.h"
+#include "GMPDecoderModule.h"
+#include "GMPService.h"
+#include "MP4Decoder.h"
+#include "MediaInfo.h"
+#include "MediaPrefs.h"
+#include "PDMFactory.h"
+#include "gmp-decryption.h"
 #include "mozIGeckoMediaPluginService.h"
 #include "mozilla/CDMProxy.h"
+#include "mozilla/EMEUtils.h"
 #include "mozilla/Unused.h"
 #include "nsAutoPtr.h"
+#include "nsClassHashtable.h"
 #include "nsServiceManagerUtils.h"
-#include "MediaInfo.h"
-#include "nsClassHashtable.h"
-#include "GMPDecoderModule.h"
-#include "MP4Decoder.h"
-#include "MediaPrefs.h"
-#include "mozilla/EMEUtils.h"
 
 namespace mozilla {
 
 typedef MozPromiseRequestHolder<DecryptPromise> DecryptPromiseRequestHolder;
 extern already_AddRefed<PlatformDecoderModule> CreateBlankDecoderModule();
 
 class EMEDecryptor : public MediaDataDecoder
 {
@@ -186,54 +188,55 @@ public:
   {
     return mDecoder->GetDescriptionName();
   }
 
 private:
   RefPtr<MediaDataDecoder> mDecoder;
   RefPtr<TaskQueue> mTaskQueue;
   RefPtr<CDMProxy> mProxy;
-  nsClassHashtable<nsRefPtrHashKey<MediaRawData>, DecryptPromiseRequestHolder> mDecrypts;
+  nsClassHashtable<nsRefPtrHashKey<MediaRawData>, DecryptPromiseRequestHolder>
+    mDecrypts;
   RefPtr<SamplesWaitingForKey> mSamplesWaitingForKey;
   MozPromiseRequestHolder<SamplesWaitingForKey::WaitForKeyPromise> mKeyRequest;
   MozPromiseHolder<DecodePromise> mDecodePromise;
   MozPromiseHolder<DecodePromise> mDrainPromise;
   MozPromiseHolder<FlushPromise> mFlushPromise;
   MozPromiseRequestHolder<DecodePromise> mDecodeRequest;
 
   bool mIsShutdown;
 };
 
-class EMEMediaDataDecoderProxy : public MediaDataDecoderProxy
+EMEMediaDataDecoderProxy::EMEMediaDataDecoderProxy(
+  already_AddRefed<AbstractThread> aProxyThread,
+  CDMProxy* aProxy,
+  const CreateDecoderParams& aParams)
+  : MediaDataDecoderProxy(Move(aProxyThread))
+  , mTaskQueue(AbstractThread::GetCurrent()->AsTaskQueue())
+  , mSamplesWaitingForKey(
+      new SamplesWaitingForKey(aProxy,
+                               aParams.mType,
+                               aParams.mOnWaitingForKeyEvent))
+  , mProxy(aProxy)
 {
-public:
-  EMEMediaDataDecoderProxy(
-    already_AddRefed<AbstractThread> aProxyThread, CDMProxy* aProxy,
-    TrackInfo::TrackType aType,
-    MediaEventProducer<TrackInfo::TrackType>* aOnWaitingForKey)
-    : MediaDataDecoderProxy(Move(aProxyThread))
-    , mTaskQueue(AbstractThread::GetCurrent()->AsTaskQueue())
-    , mSamplesWaitingForKey(
-        new SamplesWaitingForKey(aProxy, aType, aOnWaitingForKey))
-    , mProxy(aProxy)
-  {
-  }
+}
 
-  RefPtr<DecodePromise> Decode(MediaRawData* aSample) override;
-  RefPtr<FlushPromise> Flush() override;
-  RefPtr<ShutdownPromise> Shutdown() override;
-
-private:
-  RefPtr<TaskQueue> mTaskQueue;
-  RefPtr<SamplesWaitingForKey> mSamplesWaitingForKey;
-  MozPromiseRequestHolder<SamplesWaitingForKey::WaitForKeyPromise> mKeyRequest;
-  MozPromiseHolder<DecodePromise> mDecodePromise;
-  MozPromiseRequestHolder<DecodePromise> mDecodeRequest;
-  RefPtr<CDMProxy> mProxy;
-};
+EMEMediaDataDecoderProxy::EMEMediaDataDecoderProxy(
+  const CreateDecoderParams& aParams,
+  already_AddRefed<MediaDataDecoder> aProxyDecoder,
+  CDMProxy* aProxy)
+  : MediaDataDecoderProxy(Move(aProxyDecoder))
+  , mTaskQueue(AbstractThread::GetCurrent()->AsTaskQueue())
+  , mSamplesWaitingForKey(
+      new SamplesWaitingForKey(aProxy,
+                               aParams.mType,
+                               aParams.mOnWaitingForKeyEvent))
+  , mProxy(aProxy)
+{
+}
 
 RefPtr<MediaDataDecoder::DecodePromise>
 EMEMediaDataDecoderProxy::Decode(MediaRawData* aSample)
 {
   RefPtr<DecodePromise> p = mDecodePromise.Ensure(__func__);
 
   RefPtr<EMEMediaDataDecoderProxy> self = this;
   mSamplesWaitingForKey->WaitIfKeyNotUsable(aSample)
@@ -290,26 +293,27 @@ EMEDecoderModule::EMEDecoderModule(CDMPr
 
 EMEDecoderModule::~EMEDecoderModule()
 {
 }
 
 static already_AddRefed<MediaDataDecoderProxy>
 CreateDecoderWrapper(CDMProxy* aProxy, const CreateDecoderParams& aParams)
 {
-  RefPtr<gmp::GeckoMediaPluginService> s(gmp::GeckoMediaPluginService::GetGeckoMediaPluginService());
+  RefPtr<gmp::GeckoMediaPluginService> s(
+    gmp::GeckoMediaPluginService::GetGeckoMediaPluginService());
   if (!s) {
     return nullptr;
   }
   RefPtr<AbstractThread> thread(s->GetAbstractGMPThread());
   if (!thread) {
     return nullptr;
   }
   RefPtr<MediaDataDecoderProxy> decoder(new EMEMediaDataDecoderProxy(
-    thread.forget(), aProxy, aParams.mType, aParams.mOnWaitingForKeyEvent));
+    thread.forget(), aProxy, aParams));
   return decoder.forget();
 }
 
 already_AddRefed<MediaDataDecoder>
 EMEDecoderModule::CreateVideoDecoder(const CreateDecoderParams& aParams)
 {
   MOZ_ASSERT(aParams.mConfig.mCrypto.mValid);
 
--- a/dom/media/platforms/agnostic/eme/EMEDecoderModule.h
+++ b/dom/media/platforms/agnostic/eme/EMEDecoderModule.h
@@ -2,48 +2,72 @@
 /* vim:set ts=2 sw=2 sts=2 et cindent: */
 /* 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/. */
 
 #if !defined(EMEDecoderModule_h_)
 #define EMEDecoderModule_h_
 
+#include "MediaDataDecoderProxy.h"
 #include "PlatformDecoderModule.h"
-#include "PDMFactory.h"
-#include "gmp-decryption.h"
+#include "PlatformDecoderModule.h"
+#include "SamplesWaitingForKey.h"
 
 namespace mozilla {
 
 class CDMProxy;
+class PDMFactory;
 
 class EMEDecoderModule : public PlatformDecoderModule
 {
 public:
   EMEDecoderModule(CDMProxy* aProxy, PDMFactory* aPDM);
 
-  virtual ~EMEDecoderModule();
-
 protected:
   // Decode thread.
   already_AddRefed<MediaDataDecoder>
   CreateVideoDecoder(const CreateDecoderParams& aParams) override;
 
   // Decode thread.
   already_AddRefed<MediaDataDecoder>
   CreateAudioDecoder(const CreateDecoderParams& aParams) override;
 
   ConversionRequired
   DecoderNeedsConversion(const TrackInfo& aConfig) const override;
 
   bool
-  SupportsMimeType(const nsACString& aMimeType,
-                   DecoderDoctorDiagnostics* aDiagnostics) const override;
+  SupportsMimeType(const nsACString &aMimeType,
+                   DecoderDoctorDiagnostics *aDiagnostics) const override;
 
 private:
+  virtual ~EMEDecoderModule();
   RefPtr<CDMProxy> mProxy;
   // Will be null if CDM has decoding capability.
   RefPtr<PDMFactory> mPDM;
 };
 
+class EMEMediaDataDecoderProxy : public MediaDataDecoderProxy
+{
+public:
+  EMEMediaDataDecoderProxy(
+    already_AddRefed<AbstractThread> aProxyThread, CDMProxy* aProxy,
+    const CreateDecoderParams& aParams);
+  EMEMediaDataDecoderProxy(const CreateDecoderParams& aParams,
+                           already_AddRefed<MediaDataDecoder> aProxyDecoder,
+                           CDMProxy* aProxy);
+
+  RefPtr<DecodePromise> Decode(MediaRawData* aSample) override;
+  RefPtr<FlushPromise> Flush() override;
+  RefPtr<ShutdownPromise> Shutdown() override;
+
+private:
+  RefPtr<TaskQueue> mTaskQueue;
+  RefPtr<SamplesWaitingForKey> mSamplesWaitingForKey;
+  MozPromiseRequestHolder<SamplesWaitingForKey::WaitForKeyPromise> mKeyRequest;
+  MozPromiseHolder<DecodePromise> mDecodePromise;
+  MozPromiseRequestHolder<DecodePromise> mDecodeRequest;
+  RefPtr<CDMProxy> mProxy;
+};
+
 } // namespace mozilla
 
 #endif // EMEDecoderModule_h_
--- a/dom/media/platforms/agnostic/eme/EMEVideoDecoder.cpp
+++ b/dom/media/platforms/agnostic/eme/EMEVideoDecoder.cpp
@@ -1,21 +1,21 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim:set ts=2 sw=2 sts=2 et cindent: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
-#include "mozilla/CDMProxy.h"
 #include "EMEVideoDecoder.h"
 #include "GMPVideoEncodedFrameImpl.h"
+#include "MP4Decoder.h"
 #include "MediaData.h"
-#include "MP4Decoder.h"
 #include "PlatformDecoderModule.h"
 #include "VPXDecoder.h"
+#include "mozilla/CDMProxy.h"
 
 namespace mozilla {
 
 EMEVideoDecoder::EMEVideoDecoder(CDMProxy* aProxy,
                                  const GMPVideoDecoderParams& aParams)
   : GMPVideoDecoder(GMPVideoDecoderParams(aParams))
   , mProxy(aProxy)
   , mDecryptorId(aProxy->GetDecryptorId())
@@ -40,16 +40,18 @@ nsCString
 EMEVideoDecoder::GetNodeId()
 {
   return mProxy->GetNodeId();
 }
 
 GMPUniquePtr<GMPVideoEncodedFrame>
 EMEVideoDecoder::CreateFrame(MediaRawData* aSample)
 {
-  GMPUniquePtr<GMPVideoEncodedFrame> frame = GMPVideoDecoder::CreateFrame(aSample);
+  GMPUniquePtr<GMPVideoEncodedFrame> frame =
+    GMPVideoDecoder::CreateFrame(aSample);
   if (frame && aSample->mCrypto.mValid) {
-    static_cast<gmp::GMPVideoEncodedFrameImpl*>(frame.get())->InitCrypto(aSample->mCrypto);
+    static_cast<gmp::GMPVideoEncodedFrameImpl*>(frame.get())
+      ->InitCrypto(aSample->mCrypto);
   }
   return frame;
 }
 
 } // namespace mozilla
--- a/dom/media/platforms/agnostic/eme/EMEVideoDecoder.h
+++ b/dom/media/platforms/agnostic/eme/EMEVideoDecoder.h
@@ -10,25 +10,27 @@
 #include "GMPVideoDecoder.h"
 
 namespace mozilla {
 
 class CDMProxy;
 class MediaRawData;
 class TaskQueue;
 
-class EMEVideoDecoder : public GMPVideoDecoder {
+class EMEVideoDecoder : public GMPVideoDecoder
+{
 public:
   EMEVideoDecoder(CDMProxy* aProxy, const GMPVideoDecoderParams& aParams);
 
 private:
   void InitTags(nsTArray<nsCString>& aTags) override;
   nsCString GetNodeId() override;
   uint32_t DecryptorId() const override { return mDecryptorId; }
-  GMPUniquePtr<GMPVideoEncodedFrame> CreateFrame(MediaRawData* aSample) override;
+  GMPUniquePtr<GMPVideoEncodedFrame>
+  CreateFrame(MediaRawData* aSample) override;
 
   RefPtr<CDMProxy> mProxy;
   uint32_t mDecryptorId;
 };
 
 } // namespace mozilla
 
 #endif // EMEVideoDecoder_h_
--- a/dom/media/platforms/agnostic/eme/SamplesWaitingForKey.cpp
+++ b/dom/media/platforms/agnostic/eme/SamplesWaitingForKey.cpp
@@ -1,20 +1,20 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 
-#include "mozilla/CDMProxy.h"
-#include "mozilla/CDMCaps.h"
-#include "mozilla/TaskQueue.h"
+#include "SamplesWaitingForKey.h"
 #include "MediaData.h"
 #include "MediaEventSource.h"
-#include "SamplesWaitingForKey.h"
+#include "mozilla/CDMCaps.h"
+#include "mozilla/CDMProxy.h"
+#include "mozilla/TaskQueue.h"
 
 namespace mozilla {
 
 SamplesWaitingForKey::SamplesWaitingForKey(
   CDMProxy* aProxy, TrackInfo::TrackType aType,
   MediaEventProducer<TrackInfo::TrackType>* aOnWaitingForKey)
   : mMutex("SamplesWaitingForKey")
   , mProxy(aProxy)
--- a/dom/media/platforms/agnostic/eme/SamplesWaitingForKey.h
+++ b/dom/media/platforms/agnostic/eme/SamplesWaitingForKey.h
@@ -2,20 +2,20 @@
 /* vim:set ts=2 sw=2 sts=2 et cindent: */
 /* 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 SamplesWaitingForKey_h_
 #define SamplesWaitingForKey_h_
 
+#include "MediaInfo.h"
 #include "mozilla/MozPromise.h"
 #include "mozilla/Mutex.h"
 #include "mozilla/RefPtr.h"
-#include "MediaInfo.h"
 
 namespace mozilla {
 
 typedef nsTArray<uint8_t> CencKeyId;
 
 class CDMProxy;
 template <typename... Es> class MediaEventProducer;
 class MediaRawData;
@@ -25,18 +25,20 @@ class MediaRawData;
 class SamplesWaitingForKey
 {
 public:
   NS_INLINE_DECL_THREADSAFE_REFCOUNTING(SamplesWaitingForKey)
 
   typedef MozPromise<RefPtr<MediaRawData>, bool, /* IsExclusive = */ true>
     WaitForKeyPromise;
 
-  SamplesWaitingForKey(CDMProxy* aProxy, TrackInfo::TrackType aType,
-                       MediaEventProducer<TrackInfo::TrackType>* aOnWaitingForKey);
+  SamplesWaitingForKey(
+    CDMProxy* aProxy,
+    TrackInfo::TrackType aType,
+    MediaEventProducer<TrackInfo::TrackType>* aOnWaitingForKey);
 
   // Returns a promise that will be resolved if or when a key for decoding the
   // sample becomes usable.
   RefPtr<WaitForKeyPromise> WaitIfKeyNotUsable(MediaRawData* aSample);
 
   void NotifyUsable(const CencKeyId& aKeyId);
 
   void Flush();
--- a/dom/media/platforms/agnostic/gmp/GMPDecoderModule.cpp
+++ b/dom/media/platforms/agnostic/gmp/GMPDecoderModule.cpp
@@ -1,27 +1,28 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim:set ts=2 sw=2 sts=2 et cindent: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+#include "DecoderDoctorDiagnostics.h"
 #include "GMPDecoderModule.h"
-#include "DecoderDoctorDiagnostics.h"
+#include "GMPService.h"
+#include "GMPUtils.h"
 #include "GMPVideoDecoder.h"
-#include "GMPUtils.h"
+#include "MP4Decoder.h"
 #include "MediaDataDecoderProxy.h"
 #include "MediaPrefs.h"
+#include "VPXDecoder.h"
 #include "VideoUtils.h"
+#include "gmp-video-decode.h"
 #include "mozIGeckoMediaPluginService.h"
-#include "nsServiceManagerUtils.h"
 #include "mozilla/StaticMutex.h"
-#include "gmp-video-decode.h"
-#include "MP4Decoder.h"
-#include "VPXDecoder.h"
+#include "nsServiceManagerUtils.h"
 #ifdef XP_WIN
 #include "WMFDecoderModule.h"
 #endif
 
 namespace mozilla {
 
 GMPDecoderModule::GMPDecoderModule()
 {
@@ -29,34 +30,36 @@ GMPDecoderModule::GMPDecoderModule()
 
 GMPDecoderModule::~GMPDecoderModule()
 {
 }
 
 static already_AddRefed<MediaDataDecoderProxy>
 CreateDecoderWrapper()
 {
-  RefPtr<gmp::GeckoMediaPluginService> s(gmp::GeckoMediaPluginService::GetGeckoMediaPluginService());
+  RefPtr<gmp::GeckoMediaPluginService> s(
+    gmp::GeckoMediaPluginService::GetGeckoMediaPluginService());
   if (!s) {
     return nullptr;
   }
   RefPtr<AbstractThread> thread(s->GetAbstractGMPThread());
   if (!thread) {
     return nullptr;
   }
-  RefPtr<MediaDataDecoderProxy> decoder(new MediaDataDecoderProxy(thread.forget()));
+  RefPtr<MediaDataDecoderProxy> decoder(
+    new MediaDataDecoderProxy(thread.forget()));
   return decoder.forget();
 }
 
 already_AddRefed<MediaDataDecoder>
 GMPDecoderModule::CreateVideoDecoder(const CreateDecoderParams& aParams)
 {
-  if (!MP4Decoder::IsH264(aParams.mConfig.mMimeType) &&
-      !VPXDecoder::IsVP8(aParams.mConfig.mMimeType) &&
-      !VPXDecoder::IsVP9(aParams.mConfig.mMimeType)) {
+  if (!MP4Decoder::IsH264(aParams.mConfig.mMimeType)
+      && !VPXDecoder::IsVP8(aParams.mConfig.mMimeType)
+      && !VPXDecoder::IsVP9(aParams.mConfig.mMimeType)) {
     return nullptr;
   }
 
   RefPtr<MediaDataDecoderProxy> wrapper = CreateDecoderWrapper();
   auto params = GMPVideoDecoderParams(aParams);
   wrapper->SetProxyTarget(new GMPVideoDecoder(params));
   return wrapper.forget();
 }
@@ -65,17 +68,18 @@ already_AddRefed<MediaDataDecoder>
 GMPDecoderModule::CreateAudioDecoder(const CreateDecoderParams& aParams)
 {
   return nullptr;
 }
 
 PlatformDecoderModule::ConversionRequired
 GMPDecoderModule::DecoderNeedsConversion(const TrackInfo& aConfig) const
 {
-  // GMPVideoCodecType::kGMPVideoCodecH264 specifies that encoded frames must be in AVCC format.
+  // GMPVideoCodecType::kGMPVideoCodecH264 specifies that encoded frames must be
+  // in AVCC format.
   if (aConfig.IsVideo() && MP4Decoder::IsH264(aConfig.mMimeType)) {
     return ConversionRequired::kNeedAVCC;
   } else {
     return ConversionRequired::kNeedNone;
   }
 }
 
 /* static */
--- a/dom/media/platforms/agnostic/gmp/GMPDecoderModule.h
+++ b/dom/media/platforms/agnostic/gmp/GMPDecoderModule.h
@@ -20,22 +20,21 @@
 // world is through the EME GMP APIs, and we never run EME with this NodeID
 // (because NodeIds are random strings which can't contain the '-' character),
 // so there's no way a malicious GMP can harvest, store, and then report any
 // privacy sensitive data about what users are watching.
 #define SHARED_GMP_DECODING_NODE_ID NS_LITERAL_CSTRING("gmp-shared-decoding")
 
 namespace mozilla {
 
-class GMPDecoderModule : public PlatformDecoderModule {
+class GMPDecoderModule : public PlatformDecoderModule
+{
 public:
   GMPDecoderModule();
 
-  virtual ~GMPDecoderModule();
-
   // Decode thread.
   already_AddRefed<MediaDataDecoder>
   CreateVideoDecoder(const CreateDecoderParams& aParams) override;
 
   // Decode thread.
   already_AddRefed<MediaDataDecoder>
   CreateAudioDecoder(const CreateDecoderParams& aParams) override;
 
@@ -43,13 +42,16 @@ public:
   DecoderNeedsConversion(const TrackInfo& aConfig) const override;
 
   bool
   SupportsMimeType(const nsACString& aMimeType,
                    DecoderDoctorDiagnostics* aDiagnostics) const override;
 
   static bool SupportsMimeType(const nsACString& aMimeType,
                                const Maybe<nsCString>& aGMP);
+
+private:
+  virtual ~GMPDecoderModule();
 };
 
 } // namespace mozilla
 
 #endif // GMPDecoderModule_h_
--- a/dom/media/platforms/agnostic/gmp/GMPVideoDecoder.cpp
+++ b/dom/media/platforms/agnostic/gmp/GMPVideoDecoder.cpp
@@ -1,28 +1,29 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim:set ts=2 sw=2 sts=2 et cindent: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "GMPVideoDecoder.h"
+#include "GMPDecoderModule.h"
 #include "GMPVideoHost.h"
+#include "MediaData.h"
+#include "VPXDecoder.h"
 #include "mozilla/EndianUtils.h"
 #include "prsystem.h"
-#include "MediaData.h"
-#include "GMPDecoderModule.h"
-#include "VPXDecoder.h"
 
 namespace mozilla {
 
 #if defined(DEBUG)
 static bool IsOnGMPThread()
 {
-  nsCOMPtr<mozIGeckoMediaPluginService> mps = do_GetService("@mozilla.org/gecko-media-plugin-service;1");
+  nsCOMPtr<mozIGeckoMediaPluginService> mps =
+    do_GetService("@mozilla.org/gecko-media-plugin-service;1");
   MOZ_ASSERT(mps);
 
   nsCOMPtr<nsIThread> gmpThread;
   nsresult rv = mps->GetThread(getter_AddRefs(gmpThread));
   MOZ_ASSERT(NS_SUCCEEDED(rv) && gmpThread);
   return NS_GetCurrentThread() == gmpThread;
 }
 #endif
@@ -53,17 +54,18 @@ GMPVideoDecoder::Decoded(GMPVideoi420Fra
     } else {
       b.mPlanes[i].mWidth = (decodedFrame->Width() + 1) / 2;
       b.mPlanes[i].mHeight = (decodedFrame->Height() + 1) / 2;
     }
     b.mPlanes[i].mOffset = 0;
     b.mPlanes[i].mSkip = 0;
   }
 
-  gfx::IntRect pictureRegion(0, 0, decodedFrame->Width(), decodedFrame->Height());
+  gfx::IntRect pictureRegion(
+    0, 0, decodedFrame->Width(), decodedFrame->Height());
   RefPtr<VideoData> v =
     VideoData::CreateAndCopyData(mConfig,
                                  mImageContainer,
                                  mLastStreamOffset,
                                  decodedFrame->Timestamp(),
                                  decodedFrame->Duration(),
                                  b,
                                  false,
@@ -167,17 +169,18 @@ GMPUniquePtr<GMPVideoEncodedFrame>
 GMPVideoDecoder::CreateFrame(MediaRawData* aSample)
 {
   GMPVideoFrame* ftmp = nullptr;
   GMPErr err = mHost->CreateFrame(kGMPEncodedVideoFrame, &ftmp);
   if (GMP_FAILED(err)) {
     return nullptr;
   }
 
-  GMPUniquePtr<GMPVideoEncodedFrame> frame(static_cast<GMPVideoEncodedFrame*>(ftmp));
+  GMPUniquePtr<GMPVideoEncodedFrame> frame(
+    static_cast<GMPVideoEncodedFrame*>(ftmp));
   err = frame->CreateEmptyFrame(aSample->Size());
   if (GMP_FAILED(err)) {
     return nullptr;
   }
 
   memcpy(frame->Buffer(), aSample->Data(), frame->Size());
 
   // Convert 4-byte NAL unit lengths to host-endian 4-byte buffer lengths to
@@ -323,17 +326,18 @@ GMPVideoDecoder::Decode(MediaRawData* aS
                   RESULT_DETAIL("CreateFrame returned null")),
       __func__);
   }
   RefPtr<DecodePromise> p = mDecodePromise.Ensure(__func__);
   nsTArray<uint8_t> info; // No codec specific per-frame info to pass.
   nsresult rv = mGMP->Decode(Move(frame), false, info, 0);
   if (NS_FAILED(rv)) {
     mDecodePromise.Reject(MediaResult(NS_ERROR_DOM_MEDIA_DECODE_ERR,
-                                      RESULT_DETAIL("mGMP->Decode:%x", rv)),
+                                      RESULT_DETAIL("mGMP->Decode:%" PRIx32,
+                                                    static_cast<uint32_t>(rv))),
                           __func__);
   }
   return p;
 }
 
 RefPtr<MediaDataDecoder::FlushPromise>
 GMPVideoDecoder::Flush()
 {
--- a/dom/media/platforms/agnostic/gmp/GMPVideoDecoder.h
+++ b/dom/media/platforms/agnostic/gmp/GMPVideoDecoder.h
@@ -5,19 +5,19 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #if !defined(GMPVideoDecoder_h_)
 #define GMPVideoDecoder_h_
 
 #include "GMPVideoDecoderProxy.h"
 #include "ImageContainer.h"
 #include "MediaDataDecoderProxy.h"
+#include "MediaInfo.h"
 #include "PlatformDecoderModule.h"
 #include "mozIGeckoMediaPluginService.h"
-#include "MediaInfo.h"
 
 namespace mozilla {
 
 struct GMPVideoDecoderParams
 {
   explicit GMPVideoDecoderParams(const CreateDecoderParams& aParams);
 
   const VideoInfo& mConfig;
--- a/dom/media/platforms/agnostic/gmp/moz.build
+++ b/dom/media/platforms/agnostic/gmp/moz.build
@@ -2,21 +2,19 @@
 # vim: set filetype=python:
 # 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/.
 
 EXPORTS += [
     'GMPDecoderModule.h',
     'GMPVideoDecoder.h',
-    'MediaDataDecoderProxy.h',
 ]
 
 UNIFIED_SOURCES += [
     'GMPDecoderModule.cpp',
     'GMPVideoDecoder.cpp',
-    'MediaDataDecoderProxy.cpp',
 ]
 
 # GMPVideoEncodedFrameImpl.h needs IPC
 include('/ipc/chromium/chromium-config.mozbuild')
 
 FINAL_LIBRARY = 'xul'
--- a/dom/media/platforms/android/AndroidDecoderModule.cpp
+++ b/dom/media/platforms/android/AndroidDecoderModule.cpp
@@ -1,36 +1,34 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "AndroidDecoderModule.h"
 #include "AndroidBridge.h"
-
-#include "MediaCodecDataDecoder.h"
-#include "RemoteDataDecoder.h"
-
 #include "MediaInfo.h"
-#include "VPXDecoder.h"
-
 #include "MediaPrefs.h"
 #include "OpusDecoder.h"
+#include "RemoteDataDecoder.h"
+#include "VPXDecoder.h"
 #include "VorbisDecoder.h"
 
+#include "nsIGfxInfo.h"
 #include "nsPromiseFlatString.h"
-#include "nsIGfxInfo.h"
 
 #include "prlog.h"
 
 #include <jni.h>
 
 #undef LOG
-#define LOG(arg, ...) MOZ_LOG(sAndroidDecoderModuleLog, \
-    mozilla::LogLevel::Debug, ("AndroidDecoderModule(%p)::%s: " arg, \
-      this, __func__, ##__VA_ARGS__))
+#define LOG(arg, ...)                                                          \
+  MOZ_LOG(                                                                     \
+    sAndroidDecoderModuleLog,                                                  \
+    mozilla::LogLevel::Debug,                                                  \
+    ("AndroidDecoderModule(%p)::%s: " arg, this, __func__, ##__VA_ARGS__))
 
 using namespace mozilla;
 using namespace mozilla::gl;
 using namespace mozilla::java::sdk;
 using media::TimeUnit;
 
 namespace mozilla {
 
@@ -121,51 +119,52 @@ GetCryptoInfoFromSample(const MediaRawDa
 }
 
 AndroidDecoderModule::AndroidDecoderModule(CDMProxy* aProxy)
 {
   mProxy = static_cast<MediaDrmCDMProxy*>(aProxy);
 }
 
 bool
-AndroidDecoderModule::SupportsMimeType(const nsACString& aMimeType,
-                                       DecoderDoctorDiagnostics* aDiagnostics) const
+AndroidDecoderModule::SupportsMimeType(
+  const nsACString& aMimeType,
+  DecoderDoctorDiagnostics* aDiagnostics) const
 {
   if (!AndroidBridge::Bridge() ||
       AndroidBridge::Bridge()->GetAPIVersion() < 16) {
     return false;
   }
 
   if (aMimeType.EqualsLiteral("video/mp4") ||
       aMimeType.EqualsLiteral("video/avc")) {
     return true;
   }
 
   // When checking "audio/x-wav", CreateDecoder can cause a JNI ERROR by
   // Accessing a stale local reference leading to a SIGSEGV crash.
   // To avoid this we check for wav types here.
-  if (aMimeType.EqualsLiteral("audio/x-wav") ||
-      aMimeType.EqualsLiteral("audio/wave; codecs=1") ||
-      aMimeType.EqualsLiteral("audio/wave; codecs=6") ||
-      aMimeType.EqualsLiteral("audio/wave; codecs=7") ||
-      aMimeType.EqualsLiteral("audio/wave; codecs=65534")) {
+  if (aMimeType.EqualsLiteral("audio/x-wav")
+      || aMimeType.EqualsLiteral("audio/wave; codecs=1")
+      || aMimeType.EqualsLiteral("audio/wave; codecs=6")
+      || aMimeType.EqualsLiteral("audio/wave; codecs=7")
+      || aMimeType.EqualsLiteral("audio/wave; codecs=65534")) {
     return false;
   }
 
-  if ((VPXDecoder::IsVPX(aMimeType, VPXDecoder::VP8) &&
-       !GetFeatureStatus(nsIGfxInfo::FEATURE_VP8_HW_DECODE)) ||
-      (VPXDecoder::IsVPX(aMimeType, VPXDecoder::VP9) &&
-       !GetFeatureStatus(nsIGfxInfo::FEATURE_VP9_HW_DECODE))) {
+  if ((VPXDecoder::IsVPX(aMimeType, VPXDecoder::VP8)
+       && !GetFeatureStatus(nsIGfxInfo::FEATURE_VP8_HW_DECODE))
+      || (VPXDecoder::IsVPX(aMimeType, VPXDecoder::VP9)
+          && !GetFeatureStatus(nsIGfxInfo::FEATURE_VP9_HW_DECODE))) {
     return false;
   }
 
   // Prefer the gecko decoder for opus and vorbis; stagefright crashes
   // on content demuxed from mp4.
-  if (OpusDataDecoder::IsOpus(aMimeType) ||
-      VorbisDataDecoder::IsVorbis(aMimeType)) {
+  if (OpusDataDecoder::IsOpus(aMimeType)
+      || VorbisDataDecoder::IsVorbis(aMimeType)) {
     LOG("Rejecting audio of type %s", aMimeType.Data());
     return false;
   }
 
   return java::HardwareCodecCapabilityUtils::FindDecoderCodecInfoForMimeType(
     nsCString(TranslateMimeType(aMimeType)));
 }
 
@@ -174,70 +173,45 @@ AndroidDecoderModule::CreateVideoDecoder
 {
   // Temporary - forces use of VPXDecoder when alpha is present.
   // Bug 1263836 will handle alpha scenario once implemented. It will shift
   // the check for alpha to PDMFactory but not itself remove the need for a
   // check.
   if (aParams.VideoConfig().HasAlpha()) {
     return nullptr;
   }
-  MediaFormat::LocalRef format;
-
-  const VideoInfo& config = aParams.VideoConfig();
-  NS_ENSURE_SUCCESS(MediaFormat::CreateVideoFormat(
-      TranslateMimeType(config.mMimeType),
-      config.mDisplay.width,
-      config.mDisplay.height,
-      &format), nullptr);
 
   nsString drmStubId;
   if (mProxy) {
     drmStubId = mProxy->GetMediaDrmStubId();
   }
 
   RefPtr<MediaDataDecoder> decoder =
-    MediaPrefs::PDMAndroidRemoteCodecEnabled()
-    ? RemoteDataDecoder::CreateVideoDecoder(
-        config, format, aParams.mImageContainer, drmStubId, mProxy,
-        aParams.mTaskQueue)
-    : MediaCodecDataDecoder::CreateVideoDecoder(
-        config, format, aParams.mImageContainer, drmStubId, mProxy);
+    RemoteDataDecoder::CreateVideoDecoder(aParams, drmStubId, mProxy);
   return decoder.forget();
 }
 
 already_AddRefed<MediaDataDecoder>
 AndroidDecoderModule::CreateAudioDecoder(const CreateDecoderParams& aParams)
 {
   const AudioInfo& config = aParams.AudioConfig();
   if (config.mBitDepth != 16) {
     // We only handle 16-bit audio.
     return nullptr;
   }
 
-  MediaFormat::LocalRef format;
-
   LOG("CreateAudioFormat with mimeType=%s, mRate=%d, channels=%d",
       config.mMimeType.Data(), config.mRate, config.mChannels);
 
-  NS_ENSURE_SUCCESS(MediaFormat::CreateAudioFormat(
-      config.mMimeType,
-      config.mRate,
-      config.mChannels,
-      &format), nullptr);
-
   nsString drmStubId;
   if (mProxy) {
     drmStubId = mProxy->GetMediaDrmStubId();
   }
   RefPtr<MediaDataDecoder> decoder =
-    MediaPrefs::PDMAndroidRemoteCodecEnabled()
-    ? RemoteDataDecoder::CreateAudioDecoder(config, format, drmStubId, mProxy,
-                                            aParams.mTaskQueue)
-    : MediaCodecDataDecoder::CreateAudioDecoder(config, format, drmStubId,
-                                                mProxy);
+   RemoteDataDecoder::CreateAudioDecoder(aParams, drmStubId, mProxy);
   return decoder.forget();
 }
 
 PlatformDecoderModule::ConversionRequired
 AndroidDecoderModule::DecoderNeedsConversion(const TrackInfo& aConfig) const
 {
   if (aConfig.IsVideo()) {
     return ConversionRequired::kNeedAnnexB;
--- a/dom/media/platforms/android/AndroidDecoderModule.h
+++ b/dom/media/platforms/android/AndroidDecoderModule.h
@@ -15,25 +15,25 @@ class AndroidDecoderModule : public Plat
 public:
   already_AddRefed<MediaDataDecoder>
   CreateVideoDecoder(const CreateDecoderParams& aParams) override;
 
   already_AddRefed<MediaDataDecoder>
   CreateAudioDecoder(const CreateDecoderParams& aParams) override;
 
   AndroidDecoderModule(CDMProxy* aProxy = nullptr);
-  virtual ~AndroidDecoderModule() {}
 
   bool SupportsMimeType(const nsACString& aMimeType,
                         DecoderDoctorDiagnostics* aDiagnostics) const override;
 
   ConversionRequired
   DecoderNeedsConversion(const TrackInfo& aConfig) const override;
 
 private:
+  virtual ~AndroidDecoderModule() { }
   RefPtr<MediaDrmCDMProxy> mProxy;
 };
 
 extern LazyLogModule sAndroidDecoderModuleLog;
 
 } // namespace mozilla
 
 #endif
deleted file mode 100644
--- a/dom/media/platforms/android/MediaCodecDataDecoder.cpp
+++ /dev/null
@@ -1,771 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include "MediaCodecDataDecoder.h"
-
-#include "AndroidBridge.h"
-#include "AndroidSurfaceTexture.h"
-#include "GeneratedJNINatives.h"
-#include "GLImages.h"
-
-#include "MediaData.h"
-#include "MediaInfo.h"
-#include "VPXDecoder.h"
-
-#include "nsThreadUtils.h"
-#include "nsPromiseFlatString.h"
-#include "nsIGfxInfo.h"
-
-#include "prlog.h"
-
-#include <jni.h>
-
-#undef LOG
-#define LOG(arg, ...) MOZ_LOG(sAndroidDecoderModuleLog, \
-    mozilla::LogLevel::Debug, ("MediaCodecDataDecoder(%p)::%s: " arg, \
-      this, __func__, ##__VA_ARGS__))
-
-using namespace mozilla;
-using namespace mozilla::gl;
-using namespace mozilla::java;
-using namespace mozilla::java::sdk;
-using media::TimeUnit;
-
-namespace mozilla {
-
-static MediaCodec::LocalRef
-CreateDecoder(const nsACString& aMimeType)
-{
-  MediaCodec::LocalRef codec;
-  NS_ENSURE_SUCCESS(MediaCodec::CreateDecoderByType(TranslateMimeType(aMimeType),
-                    &codec), nullptr);
-  return codec;
-}
-
-class VideoDataDecoder : public MediaCodecDataDecoder
-{
-public:
-  VideoDataDecoder(const VideoInfo& aConfig,
-                   MediaFormat::Param aFormat,
-                   layers::ImageContainer* aImageContainer,
-                   const nsString& aDrmStubId)
-    : MediaCodecDataDecoder(MediaData::Type::VIDEO_DATA, aConfig.mMimeType,
-                            aFormat, aDrmStubId)
-    , mImageContainer(aImageContainer)
-    , mConfig(aConfig)
-  {
-
-  }
-
-  const char* GetDescriptionName() const override
-  {
-    return "Android MediaCodec video decoder";
-  }
-
-  RefPtr<InitPromise> Init() override
-  {
-    mSurfaceTexture = AndroidSurfaceTexture::Create();
-    if (!mSurfaceTexture) {
-      NS_WARNING("Failed to create SurfaceTexture for video decode\n");
-      return InitPromise::CreateAndReject(NS_ERROR_DOM_MEDIA_FATAL_ERR, __func__);
-    }
-
-    if (NS_FAILED(InitDecoder(mSurfaceTexture->JavaSurface()))) {
-      return InitPromise::CreateAndReject(NS_ERROR_DOM_MEDIA_FATAL_ERR, __func__);
-    }
-    return InitPromise::CreateAndResolve(TrackInfo::kVideoTrack, __func__);
-  }
-
-  void Cleanup() override
-  {
-  }
-
-  nsresult PostOutput(BufferInfo::Param aInfo, MediaFormat::Param aFormat,
-                      const TimeUnit& aDuration) override
-  {
-    RefPtr<layers::Image> img =
-      new SurfaceTextureImage(mSurfaceTexture.get(), mConfig.mDisplay,
-                              gl::OriginPos::BottomLeft);
-
-    nsresult rv;
-    int32_t flags;
-    NS_ENSURE_SUCCESS(rv = aInfo->Flags(&flags), rv);
-
-    bool isSync = !!(flags & MediaCodec::BUFFER_FLAG_SYNC_FRAME);
-
-    int32_t offset;
-    NS_ENSURE_SUCCESS(rv = aInfo->Offset(&offset), rv);
-
-    int64_t presentationTimeUs;
-    NS_ENSURE_SUCCESS(rv = aInfo->PresentationTimeUs(&presentationTimeUs), rv);
-
-    RefPtr<VideoData> v =
-      VideoData::CreateFromImage(mConfig,
-                                 offset,
-                                 presentationTimeUs,
-                                 aDuration.ToMicroseconds(),
-                                 img,
-                                 isSync,
-                                 presentationTimeUs,
-                                 gfx::IntRect(0, 0,
-                                              mConfig.mDisplay.width,
-                                              mConfig.mDisplay.height));
-    if (!v) {
-      return NS_ERROR_OUT_OF_MEMORY;
-    }
-    MonitorAutoLock mon(mMonitor);
-    mDecodedData.AppendElement(Move(v));
-    return NS_OK;
-  }
-
-  bool SupportDecoderRecycling() const override
-  {
-    return mIsCodecSupportAdaptivePlayback;
-  }
-
-protected:
-  layers::ImageContainer* mImageContainer;
-  const VideoInfo& mConfig;
-  RefPtr<AndroidSurfaceTexture> mSurfaceTexture;
-};
-
-class AudioDataDecoder : public MediaCodecDataDecoder
-{
-public:
-  AudioDataDecoder(const AudioInfo& aConfig, MediaFormat::Param aFormat,
-                   const nsString& aDrmStubId)
-    : MediaCodecDataDecoder(MediaData::Type::AUDIO_DATA, aConfig.mMimeType,
-                            aFormat, aDrmStubId)
-  {
-    JNIEnv* const env = jni::GetEnvForThread();
-
-    jni::ByteBuffer::LocalRef buffer(env);
-    NS_ENSURE_SUCCESS_VOID(aFormat->GetByteBuffer(NS_LITERAL_STRING("csd-0"),
-                                                  &buffer));
-
-    if (!buffer && aConfig.mCodecSpecificConfig->Length() >= 2) {
-      buffer = jni::ByteBuffer::New(
-          aConfig.mCodecSpecificConfig->Elements(),
-          aConfig.mCodecSpecificConfig->Length());
-      NS_ENSURE_SUCCESS_VOID(aFormat->SetByteBuffer(NS_LITERAL_STRING("csd-0"),
-                                                    buffer));
-    }
-  }
-
-  const char* GetDescriptionName() const override
-  {
-    return "android audio decoder";
-  }
-
-  nsresult Output(BufferInfo::Param aInfo, void* aBuffer,
-                  MediaFormat::Param aFormat, const TimeUnit& aDuration) override
-  {
-    // The output on Android is always 16-bit signed
-    nsresult rv;
-    int32_t numChannels;
-    NS_ENSURE_SUCCESS(rv =
-        aFormat->GetInteger(NS_LITERAL_STRING("channel-count"), &numChannels), rv);
-    AudioConfig::ChannelLayout layout(numChannels);
-    if (!layout.IsValid()) {
-      return NS_ERROR_FAILURE;
-    }
-
-    int32_t sampleRate;
-    NS_ENSURE_SUCCESS(rv =
-        aFormat->GetInteger(NS_LITERAL_STRING("sample-rate"), &sampleRate), rv);
-
-    int32_t size;
-    NS_ENSURE_SUCCESS(rv = aInfo->Size(&size), rv);
-
-    int32_t offset;
-    NS_ENSURE_SUCCESS(rv = aInfo->Offset(&offset), rv);
-
-#ifdef MOZ_SAMPLE_TYPE_S16
-    const int32_t numSamples = size / 2;
-#else
-#error We only support 16-bit integer PCM
-#endif
-
-    const int32_t numFrames = numSamples / numChannels;
-    AlignedAudioBuffer audio(numSamples);
-    if (!audio) {
-      return NS_ERROR_OUT_OF_MEMORY;
-    }
-
-    const uint8_t* bufferStart = static_cast<uint8_t*>(aBuffer) + offset;
-    PodCopy(audio.get(), reinterpret_cast<const AudioDataValue*>(bufferStart),
-            numSamples);
-
-    int64_t presentationTimeUs;
-    NS_ENSURE_SUCCESS(rv = aInfo->PresentationTimeUs(&presentationTimeUs), rv);
-
-    RefPtr<AudioData> data = new AudioData(0, presentationTimeUs,
-                                           aDuration.ToMicroseconds(),
-                                           numFrames,
-                                           Move(audio),
-                                           numChannels,
-                                           sampleRate);
-    MonitorAutoLock mon(mMonitor);
-    mDecodedData.AppendElement(Move(data));
-    return NS_OK;
-  }
-};
-
-already_AddRefed<MediaDataDecoder>
-MediaCodecDataDecoder::CreateAudioDecoder(const AudioInfo& aConfig,
-                                          java::sdk::MediaFormat::Param aFormat,
-                                          const nsString& aDrmStubId,
-                                          CDMProxy* aProxy)
-{
-  RefPtr<MediaDataDecoder> decoder;
-  if (!aProxy) {
-    decoder = new AudioDataDecoder(aConfig, aFormat, aDrmStubId);
-  } else {
-    // TODO in bug 1334061.
-  }
-  return decoder.forget();
-}
-
-already_AddRefed<MediaDataDecoder>
-MediaCodecDataDecoder::CreateVideoDecoder(const VideoInfo& aConfig,
-                                          java::sdk::MediaFormat::Param aFormat,
-                                          layers::ImageContainer* aImageContainer,
-                                          const nsString& aDrmStubId,
-                                          CDMProxy* aProxy)
-{
-  RefPtr<MediaDataDecoder> decoder;
-  if (!aProxy) {
-    decoder = new VideoDataDecoder(aConfig, aFormat, aImageContainer, aDrmStubId);
-  } else {
-    // TODO in bug 1334061.
-  }
-  return decoder.forget();
-}
-
-MediaCodecDataDecoder::MediaCodecDataDecoder(MediaData::Type aType,
-                                             const nsACString& aMimeType,
-                                             MediaFormat::Param aFormat,
-                                             const nsString& aDrmStubId)
-  : mType(aType)
-  , mMimeType(aMimeType)
-  , mFormat(aFormat)
-  , mInputBuffers(nullptr)
-  , mOutputBuffers(nullptr)
-  , mError(false)
-  , mMonitor("MediaCodecDataDecoder::mMonitor")
-  , mState(ModuleState::kDecoding)
-  , mDrmStubId(aDrmStubId)
-{
-  mDecodePromise.SetMonitor(&mMonitor);
-  mDrainPromise.SetMonitor(&mMonitor);
-}
-
-MediaCodecDataDecoder::~MediaCodecDataDecoder()
-{
-  Shutdown();
-}
-
-RefPtr<MediaDataDecoder::InitPromise>
-MediaCodecDataDecoder::Init()
-{
-  nsresult rv = InitDecoder(nullptr);
-
-  TrackInfo::TrackType type =
-    (mType == MediaData::AUDIO_DATA ? TrackInfo::TrackType::kAudioTrack
-                                    : TrackInfo::TrackType::kVideoTrack);
-
-  return NS_SUCCEEDED(rv) ? InitPromise::CreateAndResolve(type, __func__)
-                          : InitPromise::CreateAndReject(
-                              NS_ERROR_DOM_MEDIA_FATAL_ERR, __func__);
-}
-
-nsresult
-MediaCodecDataDecoder::InitDecoder(Surface::Param aSurface)
-{
-  mDecoder = CreateDecoder(mMimeType);
-
-  if (!mDecoder) {
-    return NS_ERROR_FAILURE;
-  }
-
-  // Check if the video codec supports adaptive playback or not.
-  if (aSurface) {
-    mIsCodecSupportAdaptivePlayback =
-      java::HardwareCodecCapabilityUtils::CheckSupportsAdaptivePlayback(mDecoder,
-        nsCString(TranslateMimeType(mMimeType)));
-    if (mIsCodecSupportAdaptivePlayback) {
-        // TODO: may need to find a way to not use hard code to decide the max w/h.
-        mFormat->SetInteger(MediaFormat::KEY_MAX_WIDTH, 1920);
-        mFormat->SetInteger(MediaFormat::KEY_MAX_HEIGHT, 1080);
-    }
-  }
-
-  MediaCrypto::LocalRef crypto = MediaDrmProxy::GetMediaCrypto(mDrmStubId);
-  bool hascrypto = !!crypto;
-  LOG("Has(%d) MediaCrypto (%s)", hascrypto,
-      NS_ConvertUTF16toUTF8(mDrmStubId).get());
-  nsresult rv;
-  NS_ENSURE_SUCCESS(rv = mDecoder->Configure(mFormat, aSurface, crypto, 0), rv);
-  NS_ENSURE_SUCCESS(rv = mDecoder->Start(), rv);
-
-  NS_ENSURE_SUCCESS(rv = ResetInputBuffers(), rv);
-  NS_ENSURE_SUCCESS(rv = ResetOutputBuffers(), rv);
-
-  nsCOMPtr<nsIRunnable> r =
-    NewRunnableMethod(this, &MediaCodecDataDecoder::DecoderLoop);
-  rv = NS_NewNamedThread("MC Decoder", getter_AddRefs(mThread), r);
-
-  return rv;
-}
-
-// This is in usec, so that's 10ms.
-static const int64_t kDecoderTimeout = 10000;
-
-#define BREAK_ON_DECODER_ERROR_LOCKED()                                        \
-  if (NS_FAILED(res)) {                                                        \
-    mError = true;                                                             \
-    mMonitor.AssertCurrentThreadOwns();                                        \
-    NS_WARNING("Exiting decoder loop due to exception");                       \
-    if (mState == ModuleState::kDrainDecoder) {                                \
-      mDrainPromise.RejectIfExists(                                            \
-        MediaResult(NS_ERROR_DOM_MEDIA_FATAL_ERR, __func__), __func__);        \
-      SetState(ModuleState::kDecoding);                                        \
-      break;                                                                   \
-    }                                                                          \
-    mDecodePromise.RejectIfExists(                                             \
-      MediaResult(NS_ERROR_DOM_MEDIA_FATAL_ERR, __func__), __func__);          \
-    break;                                                                     \
-  }
-
-#define BREAK_ON_DECODER_ERROR()                                               \
-  if (NS_FAILED(res)) {                                                        \
-    mError = true;                                                             \
-    MonitorAutoLock mon(mMonitor);                                             \
-    NS_WARNING("Exiting decoder loop due to exception");                       \
-    if (mState == ModuleState::kDrainDecoder) {                                \
-      mDrainPromise.RejectIfExists(                                            \
-        MediaResult(NS_ERROR_DOM_MEDIA_FATAL_ERR, __func__), __func__);        \
-      SetState(ModuleState::kDecoding);                                        \
-      break;                                                                   \
-    }                                                                          \
-    mDecodePromise.RejectIfExists(                                             \
-      MediaResult(NS_ERROR_DOM_MEDIA_FATAL_ERR, __func__), __func__);          \
-    break;                                                                     \
-  }
-
-nsresult
-MediaCodecDataDecoder::GetInputBuffer(
-    JNIEnv* aEnv, int aIndex, jni::Object::LocalRef* aBuffer)
-{
-  MOZ_ASSERT(aEnv);
-  MOZ_ASSERT(!*aBuffer);
-
-  int numTries = 2;
-
-  while (numTries--) {
-    *aBuffer = jni::Object::LocalRef::Adopt(
-        aEnv->GetObjectArrayElement(mInputBuffers.Get(), aIndex));
-    if (*aBuffer) {
-      return NS_OK;
-    }
-    nsresult res = ResetInputBuffers();
-    if (NS_FAILED(res)) {
-      return res;
-    }
-  }
-  return NS_ERROR_FAILURE;
-}
-
-bool
-MediaCodecDataDecoder::WaitForInput()
-{
-  MonitorAutoLock lock(mMonitor);
-
-  while (mState == ModuleState::kDecoding && mQueue.empty()) {
-    // We're done processing the current sample.
-    mDecodePromise.ResolveIfExists(mDecodedData, __func__);
-    mDecodedData.Clear();
-    lock.Wait();
-  }
-
-  return mState != ModuleState::kStopping;
-}
-
-
-already_AddRefed<MediaRawData>
-MediaCodecDataDecoder::PeekNextSample()
-{
-  MonitorAutoLock lock(mMonitor);
-
-  if (mState == ModuleState::kFlushing) {
-    mDecoder->Flush();
-    ClearQueue();
-    SetState(ModuleState::kDecoding);
-    lock.Notify();
-    return nullptr;
-  }
-
-  if (mQueue.empty()) {
-    if (mState == ModuleState::kDrainQueue) {
-      SetState(ModuleState::kDrainDecoder);
-    }
-    return nullptr;
-  }
-
-  // We're not stopping or flushing, so try to get a sample.
-  return RefPtr<MediaRawData>(mQueue.front()).forget();
-}
-
-nsresult
-MediaCodecDataDecoder::QueueSample(const MediaRawData* aSample)
-{
-  MOZ_ASSERT(aSample);
-  AutoLocalJNIFrame frame(jni::GetEnvForThread(), 1);
-
-  // We have a sample, try to feed it to the decoder.
-  int32_t inputIndex = -1;
-  nsresult res = mDecoder->DequeueInputBuffer(kDecoderTimeout, &inputIndex);
-  if (NS_FAILED(res)) {
-    return res;
-  }
-
-  if (inputIndex < 0) {
-    // There is no valid input buffer available.
-    return NS_ERROR_FAILURE;
-  }
-
-  jni::Object::LocalRef buffer(frame.GetEnv());
-  res = GetInputBuffer(frame.GetEnv(), inputIndex, &buffer);
-  if (NS_FAILED(res)) {
-    return res;
-  }
-
-  void* directBuffer = frame.GetEnv()->GetDirectBufferAddress(buffer.Get());
-
-  MOZ_ASSERT(frame.GetEnv()->GetDirectBufferCapacity(buffer.Get()) >=
-             aSample->Size(),
-             "Decoder buffer is not large enough for sample");
-
-  PodCopy(static_cast<uint8_t*>(directBuffer), aSample->Data(), aSample->Size());
-
-  CryptoInfo::LocalRef cryptoInfo = GetCryptoInfoFromSample(aSample);
-  if (cryptoInfo) {
-    res = mDecoder->QueueSecureInputBuffer(inputIndex, 0, cryptoInfo,
-                                           aSample->mTime, 0);
-  } else {
-    res = mDecoder->QueueInputBuffer(inputIndex, 0, aSample->Size(),
-                                     aSample->mTime, 0);
-  }
-
-  if (NS_FAILED(res)) {
-    return res;
-  }
-
-  mDurations.push_back(TimeUnit::FromMicroseconds(aSample->mDuration));
-  return NS_OK;
-}
-
-nsresult
-MediaCodecDataDecoder::QueueEOS()
-{
-  mMonitor.AssertCurrentThreadOwns();
-
-  nsresult res = NS_OK;
-  int32_t inputIndex = -1;
-  res = mDecoder->DequeueInputBuffer(kDecoderTimeout, &inputIndex);
-  if (NS_FAILED(res) || inputIndex < 0) {
-    return res;
-  }
-
-  res = mDecoder->QueueInputBuffer(inputIndex, 0, 0, 0,
-                                   MediaCodec::BUFFER_FLAG_END_OF_STREAM);
-  if (NS_SUCCEEDED(res)) {
-    SetState(ModuleState::kDrainWaitEOS);
-    mMonitor.Notify();
-  }
-  return res;
-}
-
-void
-MediaCodecDataDecoder::HandleEOS(int32_t aOutputStatus)
-{
-  MonitorAutoLock lock(mMonitor);
-
-  if (mState ==  ModuleState::kDrainWaitEOS) {
-    SetState(ModuleState::kDecoding);
-
-    mDrainPromise.ResolveIfExists(mDecodedData, __func__);
-    mDecodedData.Clear();
-    mMonitor.Notify();
-  }
-
-  mDecoder->ReleaseOutputBuffer(aOutputStatus, false);
-}
-
-Maybe<TimeUnit>
-MediaCodecDataDecoder::GetOutputDuration()
-{
-  if (mDurations.empty()) {
-    return Nothing();
-  }
-  const Maybe<TimeUnit> duration = Some(mDurations.front());
-  mDurations.pop_front();
-  return duration;
-}
-
-nsresult
-MediaCodecDataDecoder::ProcessOutput(
-    BufferInfo::Param aInfo, MediaFormat::Param aFormat, int32_t aStatus)
-{
-  AutoLocalJNIFrame frame(jni::GetEnvForThread(), 1);
-
-  const Maybe<TimeUnit> duration = GetOutputDuration();
-  if (!duration) {
-    // Some devices report failure in QueueSample while actually succeeding at
-    // it, in which case we get an output buffer without having a cached duration
-    // (bug 1273523).
-    return NS_OK;
-  }
-
-  const auto buffer = jni::Object::LocalRef::Adopt(
-      frame.GetEnv()->GetObjectArrayElement(mOutputBuffers.Get(), aStatus));
-
-  if (buffer) {
-    // The buffer will be null on Android L if we are decoding to a Surface.
-    void* directBuffer = frame.GetEnv()->GetDirectBufferAddress(buffer.Get());
-    Output(aInfo, directBuffer, aFormat, duration.value());
-  }
-
-  // The Surface will be updated at this point (for video).
-  mDecoder->ReleaseOutputBuffer(aStatus, true);
-  return PostOutput(aInfo, aFormat, duration.value());
-}
-
-void
-MediaCodecDataDecoder::DecoderLoop()
-{
-  bool isOutputDone = false;
-  AutoLocalJNIFrame frame(jni::GetEnvForThread(), 1);
-  MediaFormat::LocalRef outputFormat(frame.GetEnv());
-  nsresult res = NS_OK;
-
-  while (WaitForInput()) {
-    RefPtr<MediaRawData> sample = PeekNextSample();
-
-    {
-      MonitorAutoLock lock(mMonitor);
-      if (mState == ModuleState::kDrainDecoder) {
-        MOZ_ASSERT(!sample, "Shouldn't have a sample when pushing EOF frame");
-        res = QueueEOS();
-        BREAK_ON_DECODER_ERROR_LOCKED();
-      }
-    }
-
-    if (sample) {
-      res = QueueSample(sample);
-      if (NS_SUCCEEDED(res)) {
-        // We've fed this into the decoder, so remove it from the queue.
-        MonitorAutoLock lock(mMonitor);
-        MOZ_RELEASE_ASSERT(mQueue.size(), "Queue may not be empty");
-        mQueue.pop_front();
-        isOutputDone = false;
-      }
-    }
-
-    if (isOutputDone) {
-      continue;
-    }
-
-    BufferInfo::LocalRef bufferInfo;
-    nsresult res = BufferInfo::New(&bufferInfo);
-    BREAK_ON_DECODER_ERROR();
-
-    int32_t outputStatus = -1;
-    res = mDecoder->DequeueOutputBuffer(bufferInfo, kDecoderTimeout,
-                                        &outputStatus);
-    BREAK_ON_DECODER_ERROR();
-
-    if (outputStatus == MediaCodec::INFO_TRY_AGAIN_LATER) {
-    } else if (outputStatus == MediaCodec::INFO_OUTPUT_BUFFERS_CHANGED) {
-      res = ResetOutputBuffers();
-      BREAK_ON_DECODER_ERROR();
-    } else if (outputStatus == MediaCodec::INFO_OUTPUT_FORMAT_CHANGED) {
-      res = mDecoder->GetOutputFormat(ReturnTo(&outputFormat));
-      BREAK_ON_DECODER_ERROR();
-    } else if (outputStatus < 0) {
-      NS_WARNING("Unknown error from decoder!");
-      {
-        const auto result =
-          MediaResult(NS_ERROR_DOM_MEDIA_DECODE_ERR, __func__);
-        MonitorAutoLock mon(mMonitor);
-        mDecodePromise.RejectIfExists(result, __func__);
-        mDrainPromise.RejectIfExists(result, __func__);
-      }
-      // Don't break here just in case it's recoverable. If it's not, other
-      // stuff will fail later and we'll bail out.
-    } else {
-      // We have a valid buffer index >= 0 here.
-      int32_t flags;
-      nsresult res = bufferInfo->Flags(&flags);
-      BREAK_ON_DECODER_ERROR();
-
-      if (flags & MediaCodec::BUFFER_FLAG_END_OF_STREAM) {
-        HandleEOS(outputStatus);
-        isOutputDone = true;
-        // We only queue empty EOF frames, so we're done for now.
-        continue;
-      }
-
-      res = ProcessOutput(bufferInfo, outputFormat, outputStatus);
-      BREAK_ON_DECODER_ERROR();
-    }
-  }
-
-  Cleanup();
-
-  // We're done.
-  MonitorAutoLock lock(mMonitor);
-  SetState(ModuleState::kShutdown);
-  mMonitor.Notify();
-}
-
-const char*
-MediaCodecDataDecoder::ModuleStateStr(ModuleState aState) {
-    switch (aState) {
-      case ModuleState::kDecoding:     return "Decoding";
-      case ModuleState::kFlushing:     return "Flushing";
-      case ModuleState::kDrainQueue:   return "DrainQueue";
-      case ModuleState::kDrainDecoder: return "DrainDecoder";
-      case ModuleState::kDrainWaitEOS: return "DrainWaitEOS";
-      case ModuleState::kStopping:     return "Stopping";
-      case ModuleState::kShutdown:     return "Shutdown";
-      default: MOZ_ASSERT_UNREACHABLE("Invalid state.");
-    }
-    return "Unknown";
-}
-
-bool
-MediaCodecDataDecoder::SetState(ModuleState aState)
-{
-  mMonitor.AssertCurrentThreadOwns();
-
-  bool ok = true;
-
-  if (mState == ModuleState::kShutdown) {
-    ok = false;
-  } else if (mState == ModuleState::kStopping) {
-    ok = aState == ModuleState::kShutdown;
-  } else if (aState == ModuleState::kDrainDecoder) {
-    ok = mState == ModuleState::kDrainQueue;
-  } else if (aState == ModuleState::kDrainWaitEOS) {
-    ok = mState == ModuleState::kDrainDecoder;
-  }
-
-  if (ok) {
-    LOG("%s -> %s", ModuleStateStr(mState), ModuleStateStr(aState));
-    mState = aState;
-  } else {
-    LOG("Fail to transit from %s to %s state", ModuleStateStr(mState), ModuleStateStr(aState));
-  }
-
-  return ok;
-}
-
-void
-MediaCodecDataDecoder::ClearQueue()
-{
-  mMonitor.AssertCurrentThreadOwns();
-
-  mQueue.clear();
-  mDurations.clear();
-  mDecodedData.Clear();
-}
-
-RefPtr<MediaDataDecoder::DecodePromise>
-MediaCodecDataDecoder::Decode(MediaRawData* aSample)
-{
-  if (mError) {
-    return DecodePromise::CreateAndReject(NS_ERROR_DOM_MEDIA_FATAL_ERR,
-                                          __func__);
-  }
-  MonitorAutoLock lock(mMonitor);
-  RefPtr<DecodePromise> p = mDecodePromise.Ensure(__func__);
-  mQueue.push_back(aSample);
-  lock.NotifyAll();
-  return p;
-}
-
-nsresult
-MediaCodecDataDecoder::ResetInputBuffers()
-{
-  return mDecoder->GetInputBuffers(ReturnTo(&mInputBuffers));
-}
-
-nsresult
-MediaCodecDataDecoder::ResetOutputBuffers()
-{
-  return mDecoder->GetOutputBuffers(ReturnTo(&mOutputBuffers));
-}
-
-RefPtr<MediaDataDecoder::FlushPromise>
-MediaCodecDataDecoder::Flush()
-{
-  MonitorAutoLock lock(mMonitor);
-  mDecodePromise.RejectIfExists(NS_ERROR_DOM_MEDIA_CANCELED, __func__);
-  mDrainPromise.RejectIfExists(NS_ERROR_DOM_MEDIA_CANCELED, __func__);
-  if (!SetState(ModuleState::kFlushing)) {
-    return FlushPromise::CreateAndResolve(true, __func__);
-  }
-  lock.Notify();
-
-  while (mState == ModuleState::kFlushing) {
-    lock.Wait();
-  }
-  return FlushPromise::CreateAndResolve(true, __func__);
-}
-
-RefPtr<MediaDataDecoder::DecodePromise>
-MediaCodecDataDecoder::Drain()
-{
-  if (mError) {
-    return DecodePromise::CreateAndReject(NS_ERROR_DOM_MEDIA_FATAL_ERR,
-                                          __func__);
-  }
-  MonitorAutoLock lock(mMonitor);
-  RefPtr<DecodePromise> p = mDecodePromise.Ensure(__func__);
-  MOZ_ASSERT(mState != ModuleState::kDrainDecoder
-             && mState != ModuleState::kDrainQueue, "Already draining");
-
-  SetState(ModuleState::kDrainQueue);
-  lock.Notify();
-  return p;
-}
-
-RefPtr<ShutdownPromise>
-MediaCodecDataDecoder::Shutdown()
-{
-  MonitorAutoLock lock(mMonitor);
-
-  SetState(ModuleState::kStopping);
-  lock.Notify();
-
-  while (mThread && mState != ModuleState::kShutdown) {
-    lock.Wait();
-  }
-
-  if (mThread) {
-    mThread->Shutdown();
-    mThread = nullptr;
-  }
-
-  if (mDecoder) {
-    mDecoder->Stop();
-    mDecoder->Release();
-    mDecoder = nullptr;
-  }
-
-  return ShutdownPromise::CreateAndResolve(true, __func__);
-}
-
-} // mozilla
deleted file mode 100644
--- a/dom/media/platforms/android/MediaCodecDataDecoder.h
+++ /dev/null
@@ -1,138 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#ifndef MediaCodecDataDecoder_h_
-#define MediaCodecDataDecoder_h_
-
-#include "AndroidDecoderModule.h"
-
-#include "MediaCodec.h"
-#include "SurfaceTexture.h"
-#include "TimeUnits.h"
-#include "mozilla/Atomics.h"
-#include "mozilla/Monitor.h"
-#include "mozilla/Maybe.h"
-
-#include <deque>
-
-namespace mozilla {
-
-typedef std::deque<RefPtr<MediaRawData>> SampleQueue;
-
-class MediaCodecDataDecoder : public MediaDataDecoder
-{
-public:
-  static already_AddRefed<MediaDataDecoder> CreateAudioDecoder(
-    const AudioInfo& aConfig, java::sdk::MediaFormat::Param aFormat,
-    const nsString& aDrmStubId, CDMProxy* aProxy);
-
-  static already_AddRefed<MediaDataDecoder> CreateVideoDecoder(
-    const VideoInfo& aConfig, java::sdk::MediaFormat::Param aFormat,
-    layers::ImageContainer* aImageContainer, const nsString& aDrmStubId,
-    CDMProxy* aProxy);
-
-  ~MediaCodecDataDecoder();
-
-  RefPtr<InitPromise> Init() override;
-  RefPtr<DecodePromise> Decode(MediaRawData* aSample) override;
-  RefPtr<DecodePromise> Drain() override;
-  RefPtr<FlushPromise> Flush() override;
-  RefPtr<ShutdownPromise> Shutdown() override;
-  const char* GetDescriptionName() const override
-  {
-    return "Android MediaCodec decoder";
-  }
-
-protected:
-  enum class ModuleState : uint8_t
-  {
-    kDecoding = 0,
-    kFlushing,
-    kDrainQueue,
-    kDrainDecoder,
-    kDrainWaitEOS,
-    kStopping,
-    kShutdown
-  };
-
-  friend class AndroidDecoderModule;
-
-  MediaCodecDataDecoder(MediaData::Type aType,
-                        const nsACString& aMimeType,
-                        java::sdk::MediaFormat::Param aFormat,
-                        const nsString& aDrmStubId);
-
-  static const char* ModuleStateStr(ModuleState aState);
-
-  virtual nsresult InitDecoder(java::sdk::Surface::Param aSurface);
-
-  virtual nsresult Output(java::sdk::BufferInfo::Param aInfo, void* aBuffer,
-      java::sdk::MediaFormat::Param aFormat, const media::TimeUnit& aDuration)
-  {
-    return NS_OK;
-  }
-
-  virtual nsresult PostOutput(java::sdk::BufferInfo::Param aInfo,
-      java::sdk::MediaFormat::Param aFormat, const media::TimeUnit& aDuration)
-  {
-    return NS_OK;
-  }
-
-  virtual void Cleanup() {};
-
-  nsresult ResetInputBuffers();
-  nsresult ResetOutputBuffers();
-
-  nsresult GetInputBuffer(JNIEnv* env, int index, jni::Object::LocalRef* buffer);
-  bool WaitForInput();
-  already_AddRefed<MediaRawData> PeekNextSample();
-  nsresult QueueSample(const MediaRawData* aSample);
-  nsresult QueueEOS();
-  void HandleEOS(int32_t aOutputStatus);
-  Maybe<media::TimeUnit> GetOutputDuration();
-  nsresult ProcessOutput(java::sdk::BufferInfo::Param aInfo,
-                         java::sdk::MediaFormat::Param aFormat,
-                         int32_t aStatus);
-  // Sets decoder state and returns whether the new state has become effective.
-  // Must hold the monitor.
-  bool SetState(ModuleState aState);
-  void DecoderLoop();
-
-  virtual void ClearQueue();
-
-  MediaData::Type mType;
-
-  nsAutoCString mMimeType;
-  java::sdk::MediaFormat::GlobalRef mFormat;
-
-  java::sdk::MediaCodec::GlobalRef mDecoder;
-
-  jni::ObjectArray::GlobalRef mInputBuffers;
-  jni::ObjectArray::GlobalRef mOutputBuffers;
-
-  nsCOMPtr<nsIThread> mThread;
-
-  Atomic<bool> mError;
-
-  // Only these members are protected by mMonitor.
-  Monitor mMonitor;
-
-  ModuleState mState;
-
-  SampleQueue mQueue;
-  // Durations are stored in microseconds.
-  std::deque<media::TimeUnit> mDurations;
-
-  nsString mDrmStubId;
-
-  bool mIsCodecSupportAdaptivePlayback = false;
-
-  MozPromiseHolder<DecodePromise> mDecodePromise;
-  MozPromiseHolder<DecodePromise> mDrainPromise;
-  DecodedData mDecodedData;
-};
-
-} // namespace mozilla
-
-#endif
--- a/dom/media/platforms/android/RemoteDataDecoder.cpp
+++ b/dom/media/platforms/android/RemoteDataDecoder.cpp
@@ -1,38 +1,34 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+#include "AndroidBridge.h"
 #include "AndroidDecoderModule.h"
-#include "AndroidBridge.h"
 #include "AndroidSurfaceTexture.h"
+#include "DurationMap.h"
 #include "FennecJNINatives.h"
 #include "GLImages.h"
-
 #include "MediaData.h"
 #include "MediaInfo.h"
+#include "VPXDecoder.h"
 #include "VideoUtils.h"
-#include "VPXDecoder.h"
-
 #include "mozilla/Mutex.h"
-#include "nsThreadUtils.h"
+#include "nsIGfxInfo.h"
 #include "nsPromiseFlatString.h"
-#include "nsIGfxInfo.h"
-
+#include "nsThreadUtils.h"
 #include "prlog.h"
-
-#include "DurationMap.h"
 #include <jni.h>
 
-
 #undef LOG
-#define LOG(arg, ...) MOZ_LOG(sAndroidDecoderModuleLog, \
-    mozilla::LogLevel::Debug, ("RemoteDataDecoder(%p)::%s: " arg, \
-      this, __func__, ##__VA_ARGS__))
+#define LOG(arg, ...)                                                          \
+  MOZ_LOG(sAndroidDecoderModuleLog,                                            \
+          mozilla::LogLevel::Debug,                                            \
+          ("RemoteDataDecoder(%p)::%s: " arg, this, __func__, ##__VA_ARGS__))
 
 using namespace mozilla;
 using namespace mozilla::gl;
 using namespace mozilla::java;
 using namespace mozilla::java::sdk;
 using media::TimeUnit;
 
 namespace mozilla {
@@ -147,18 +143,18 @@ public:
 
     void HandleInputExhausted() override
     {
       mDecoder->ReturnDecodedData();
     }
 
     void HandleOutput(Sample::Param aSample) override
     {
-      UniquePtr<VideoData::Listener>
-        releaseSample(new RenderOrReleaseOutput(mDecoder->mJavaDecoder, aSample));
+      UniquePtr<VideoData::Listener> releaseSample(
+        new RenderOrReleaseOutput(mDecoder->mJavaDecoder, aSample));
 
       BufferInfo::LocalRef info = aSample->Info();
 
       int32_t flags;
       bool ok = NS_SUCCEEDED(info->Flags(&flags));
 
       int32_t offset;
       ok &= NS_SUCCEEDED(info->Offset(&offset));
@@ -172,17 +168,18 @@ public:
       if (!ok) {
         HandleError(MediaResult(NS_ERROR_DOM_MEDIA_FATAL_ERR,
                                 RESULT_DETAIL("VideoCallBack::HandleOutput")));
         return;
       }
 
       bool isEOS = !!(flags & MediaCodec::BUFFER_FLAG_END_OF_STREAM);
       int64_t durationUs = 0;
-      if (!mDecoder->mInputDurations.Find(presentationTimeUs, durationUs) && !isEOS) {
+      if (!mDecoder->mInputDurations.Find(presentationTimeUs, durationUs)
+          && !isEOS) {
         return;
       }
 
       if (size > 0) {
         MutexAutoLock lock(mDecoder->mMutex);
 
         RefPtr<layers::Image> img = new SurfaceTextureImage(
           mDecoder->mSurfaceTexture.get(), mDecoder->mConfig.mDisplay,
@@ -429,43 +426,54 @@ private:
     int32_t mOutputChannels;
     int32_t mOutputSampleRate;
   };
 
   const AudioInfo mConfig;
 };
 
 already_AddRefed<MediaDataDecoder>
-RemoteDataDecoder::CreateAudioDecoder(const AudioInfo& aConfig,
-                                      MediaFormat::Param aFormat,
+RemoteDataDecoder::CreateAudioDecoder(const CreateDecoderParams& aParams,
                                       const nsString& aDrmStubId,
-                                      CDMProxy* aProxy, TaskQueue* aTaskQueue)
+                                      CDMProxy* aProxy)
 {
-  RefPtr<MediaDataDecoder> decoder;
-  if (!aProxy) {
-    decoder = new RemoteAudioDecoder(aConfig, aFormat, aDrmStubId, aTaskQueue);
-  } else {
-    // TODO in bug 1334061.
+  const AudioInfo& config = aParams.AudioConfig();
+  MediaFormat::LocalRef format;
+  NS_ENSURE_SUCCESS(
+    MediaFormat::CreateAudioFormat(
+      config.mMimeType, config.mRate, config.mChannels, &format),
+    nullptr);
+
+  RefPtr<MediaDataDecoder> decoder =
+    new RemoteAudioDecoder(config, format, aDrmStubId, aParams.mTaskQueue);
+  if (aProxy) {
+    decoder = new EMEMediaDataDecoderProxy(aParams, decoder.forget(), aProxy);
   }
   return decoder.forget();
 }
 
 already_AddRefed<MediaDataDecoder>
-RemoteDataDecoder::CreateVideoDecoder(const VideoInfo& aConfig,
-                                      MediaFormat::Param aFormat,
-                                      layers::ImageContainer* aImageContainer,
+RemoteDataDecoder::CreateVideoDecoder(const CreateDecoderParams& aParams,
                                       const nsString& aDrmStubId,
-                                      CDMProxy* aProxy, TaskQueue* aTaskQueue)
+                                      CDMProxy* aProxy)
 {
-  RefPtr<MediaDataDecoder> decoder;
-  if (!aProxy) {
-    decoder = new RemoteVideoDecoder(aConfig, aFormat, aImageContainer,
-                                     aDrmStubId, aTaskQueue);
-  } else {
-    // TODO in bug 1334061.
+
+  const VideoInfo& config = aParams.VideoConfig();
+  MediaFormat::LocalRef format;
+  NS_ENSURE_SUCCESS(
+    MediaFormat::CreateVideoFormat(TranslateMimeType(config.mMimeType),
+                                   config.mDisplay.width,
+                                   config.mDisplay.height,
+                                   &format),
+    nullptr);
+
+  RefPtr<MediaDataDecoder> decoder = new RemoteVideoDecoder(
+    config, format, aParams.mImageContainer, aDrmStubId, aParams.mTaskQueue);
+  if (aProxy) {
+    decoder = new EMEMediaDataDecoderProxy(aParams, decoder.forget(), aProxy);
   }
   return decoder.forget();
 }
 
 RemoteDataDecoder::RemoteDataDecoder(MediaData::Type aType,
                                      const nsACString& aMimeType,
                                      MediaFormat::Param aFormat,
                                      const nsString& aDrmStubId,
--- a/dom/media/platforms/android/RemoteDataDecoder.h
+++ b/dom/media/platforms/android/RemoteDataDecoder.h
@@ -1,50 +1,48 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef RemoteDataDecoder_h_
 #define RemoteDataDecoder_h_
 
 #include "AndroidDecoderModule.h"
-
 #include "FennecJNIWrappers.h"
-
 #include "SurfaceTexture.h"
 #include "TimeUnits.h"
+#include "mozilla/Maybe.h"
 #include "mozilla/Monitor.h"
-#include "mozilla/Maybe.h"
 
 namespace mozilla {
 
 class RemoteDataDecoder : public MediaDataDecoder
 {
 public:
-  static already_AddRefed<MediaDataDecoder> CreateAudioDecoder(
-    const AudioInfo& aConfig, java::sdk::MediaFormat::Param aFormat,
-    const nsString& aDrmStubId, CDMProxy* aProxy, TaskQueue* aTaskQueue);
+  static already_AddRefed<MediaDataDecoder>
+  CreateAudioDecoder(const CreateDecoderParams& aParams,
+                     const nsString& aDrmStubId,
+                     CDMProxy* aProxy);
 
-  static already_AddRefed<MediaDataDecoder> CreateVideoDecoder(
-    const VideoInfo& aConfig, java::sdk::MediaFormat::Param aFormat,
-    layers::ImageContainer* aImageContainer, const nsString& aDrmStubId,
-    CDMProxy* aProxy, TaskQueue* aTaskQueue);
-
-  virtual ~RemoteDataDecoder() { }
+  static already_AddRefed<MediaDataDecoder>
+  CreateVideoDecoder(const CreateDecoderParams& aParams,
+                     const nsString& aDrmStubId,
+                     CDMProxy* aProxy);
 
   RefPtr<DecodePromise> Decode(MediaRawData* aSample) override;
   RefPtr<DecodePromise> Drain() override;
   RefPtr<FlushPromise> Flush() override;
   RefPtr<ShutdownPromise> Shutdown() override;
   const char* GetDescriptionName() const override
   {
     return "android remote decoder";
   }
 
 protected:
+  virtual ~RemoteDataDecoder() { }
   RemoteDataDecoder(MediaData::Type aType,