├── .babelrc
├── .eslintrc.js
├── .github
└── workflows
│ ├── publish-demo.yaml
│ ├── release-please.yml
│ ├── sync-labels.yaml
│ ├── test.yaml
│ ├── update-issues.yaml
│ └── validate-pr-title.yaml
├── .gitignore
├── CHANGELOG.md
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── SECURITY.md
├── closure-compiler-check
└── goog-stub.js
├── demo
├── index.html
├── load-tests
│ ├── load-as-es-module.html
│ ├── load-raw-source-with-script-tag.html
│ ├── load-with-requirejs.html
│ ├── load-with-script-tag.html
│ └── test-load.js
├── push-to-github-pages.sh
├── query.js
└── style.css
├── index.html
├── index.js
├── package-lock.json
└── package.json
/.babelrc:
--------------------------------------------------------------------------------
1 | {
2 | "plugins": ["babel-plugin-transform-async-to-promises"],
3 | "presets": [
4 | [
5 | "@babel/preset-env",
6 | {
7 | "targets": "last 2 versions and >1%",
8 | "loose": true
9 | }
10 | ]
11 | ]
12 | }
13 |
--------------------------------------------------------------------------------
/.eslintrc.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @license
3 | * Copyright 2019 Google LLC
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | // ESlint config
19 | module.exports = {
20 | 'env': {
21 | 'browser': true,
22 | 'es6': true,
23 | },
24 | 'parserOptions': {
25 | 'ecmaVersion': 2017,
26 | 'sourceType': 'module',
27 | },
28 | 'plugins': ['jsdoc'],
29 | 'extends': ['eslint:recommended', 'google', 'plugin:jsdoc/recommended'],
30 | 'settings': {
31 | 'jsdoc': {
32 | // Tell the jsdoc linter that we have some Closure-specific tags.
33 | 'mode': 'closure',
34 | // Use these alternatives (return, const) instead of the longer versions.
35 | // This is also for Closure compatibility.
36 | 'tagNamePreference': {
37 | 'returns': 'return',
38 | 'constant': 'const',
39 | },
40 | },
41 | },
42 | 'globals': {
43 | 'module': 'readonly', // For CommonJS/AMD export
44 | },
45 | 'rules': {
46 | // Deprecated and replaced by community jsdoc plugin:
47 | 'valid-jsdoc': 'off',
48 |
49 | // Configuration for the community plugin, on top of the recommended
50 | // defaults:
51 | 'jsdoc/no-undefined-types': [
52 | 'error',
53 | {
54 | // These types are browser-provided, so trust that they exist.
55 | 'definedTypes': [
56 | 'MediaCapabilities',
57 | 'MediaCapabilitiesDecodingInfo',
58 | 'MediaDecodingConfiguration',
59 | 'MediaKeys',
60 | 'MediaKeySystemConfiguration',
61 | 'MediaKeySystemMediaCapability',
62 | ],
63 | },
64 | ],
65 | 'jsdoc/valid-types': 'error',
66 | 'jsdoc/newline-after-description': 'error',
67 | 'jsdoc/require-param-description': 'error',
68 | 'jsdoc/require-returns-description': 'error',
69 |
70 | // Allow the special "/*!" header format used by browserify-header:
71 | 'spaced-comment': [
72 | 'error',
73 | 'always',
74 | {
75 | 'markers': ['!'],
76 | },
77 | ],
78 |
79 | // "Possible error" rules:
80 | 'no-async-promise-executor': 'error',
81 | 'no-await-in-loop': 'error',
82 | 'no-empty': ['error', {'allowEmptyCatch': true}],
83 | 'no-misleading-character-class': 'error',
84 | 'no-template-curly-in-string': 'error',
85 | 'require-atomic-updates': 'error',
86 |
87 | // "Best practices" rules:
88 | 'accessor-pairs': 'error',
89 | 'array-callback-return': 'error',
90 | // causes issues when implementing an interface
91 | 'class-methods-use-this': 'off',
92 | 'consistent-return': 'error',
93 | 'dot-location': ['error', 'property'],
94 | 'no-alert': 'error',
95 | 'no-caller': 'error',
96 | 'no-div-regex': 'error',
97 | 'no-extend-native': 'error',
98 | 'no-extra-label': 'error',
99 | 'no-floating-decimal': 'error',
100 | 'no-implicit-coercion': ['error', {'allow': ['!!']}],
101 | 'no-implied-eval': 'error',
102 | 'no-invalid-this': 'error',
103 | 'no-iterator': 'error',
104 | 'no-labels': 'error',
105 | 'no-lone-blocks': 'error',
106 | 'no-multi-spaces': ['error', {'ignoreEOLComments': true}],
107 | 'no-multi-str': 'error',
108 | 'no-new': 'error',
109 | 'no-new-func': 'error',
110 | 'no-new-wrappers': 'error',
111 | 'no-octal-escape': 'error',
112 | 'no-proto': 'error',
113 | 'no-return-assign': 'error',
114 | 'no-return-await': 'error',
115 | 'no-script-url': 'error',
116 | 'no-self-compare': 'error',
117 | 'no-sequences': 'error',
118 | 'no-throw-literal': 'error',
119 | 'no-unmodified-loop-condition': 'error',
120 | 'no-useless-call': 'error',
121 | 'no-useless-catch': 'error',
122 | 'no-useless-concat': 'error',
123 | 'no-useless-return': 'error',
124 | 'no-void': 'error',
125 | 'radix': ['error', 'always'],
126 | 'require-await': 'error',
127 | 'wrap-iife': ['error', 'inside'],
128 | 'yoda': ['error', 'never'],
129 |
130 | // "Variables" rules:
131 | 'no-label-var': 'error',
132 | 'no-shadow-restricted-names': 'error',
133 |
134 | // "Stylistic Issues" rules:
135 | 'array-bracket-newline': ['error', 'consistent'],
136 | 'block-spacing': ['error', 'always'],
137 | 'brace-style': ['error', '1tbs', {'allowSingleLine': true}],
138 | 'id-denylist': ['error', 'async'],
139 | 'lines-between-class-members': 'error',
140 | 'max-statements-per-line': ['error', {'max': 1}],
141 | 'new-parens': 'error',
142 | 'no-mixed-operators': [
143 | 'error', {
144 | 'groups': [['&', '|', '^', '~', '<<', '>>', '>>>', '&&', '||']],
145 | 'allowSamePrecedence': false,
146 | },
147 | ],
148 | 'no-restricted-syntax': [
149 | 'error',
150 | {
151 | 'selector': ':not(MethodDefinition) > FunctionExpression',
152 | 'message': 'Use arrow functions instead of "function" functions.',
153 | },
154 | {
155 | 'selector': 'CallExpression[callee.property.name="forEach"] >' +
156 | ':function[params.length=1]',
157 | 'message': 'Use for-of instead of forEach',
158 | },
159 | {
160 | 'selector': 'BinaryExpression[operator=/^([<>!=]=?)$/] > ' +
161 | 'CallExpression[callee.property.name=indexOf]',
162 | 'message': 'Use Array.includes instead of indexOf.',
163 | },
164 | ],
165 | 'no-whitespace-before-property': 'error',
166 | 'nonblock-statement-body-position': ['error', 'below'],
167 | 'operator-assignment': 'error',
168 |
169 | // "ECMAScript 6" rules:
170 | 'arrow-spacing': 'error',
171 | 'no-useless-constructor': 'error',
172 | 'prefer-arrow-callback': 'error',
173 | 'prefer-const': ['error', {'ignoreReadBeforeAssign': true}],
174 | },
175 | };
176 |
--------------------------------------------------------------------------------
/.github/workflows/publish-demo.yaml:
--------------------------------------------------------------------------------
1 | # A workflow to publish the demo to GitHub Pages.
2 | name: Publish Demo
3 |
4 | # Runs on push to main.
5 | on:
6 | push:
7 | branches:
8 | - main
9 | # For manual debugging:
10 | workflow_dispatch:
11 | inputs:
12 | ref:
13 | description: "The ref to build from."
14 | required: true
15 | type: string
16 |
17 | concurrency:
18 | group: ${{ github.workflow }}-${{ github.ref }}
19 | cancel-in-progress: true
20 |
21 | jobs:
22 | build:
23 | name: Build
24 | runs-on: ubuntu-latest
25 | steps:
26 | - name: Checkout
27 | uses: actions/checkout@v4
28 | with:
29 | ref: ${{ inputs.ref || github.ref }}
30 | persist-credentials: false
31 |
32 | - name: Build
33 | run: npm ci && npm run build
34 |
35 | - name: Clean
36 | run: rm -rf node_modules
37 |
38 | - name: Upload artifacts
39 | uses: actions/upload-pages-artifact@v3
40 | with:
41 | path: .
42 |
43 | publish:
44 | name: Publish updated demo
45 | needs: build
46 | runs-on: ubuntu-latest
47 |
48 | # Grant GITHUB_TOKEN the permissions required to deploy to Pages
49 | permissions:
50 | pages: write
51 | id-token: write
52 |
53 | # Deploy to the github-pages environment
54 | environment:
55 | name: github-pages
56 | url: ${{ steps.deployment.outputs.page_url }}
57 |
58 | steps:
59 | - name: Deploy to GitHub Pages
60 | id: deployment
61 | uses: actions/deploy-pages@v4
62 |
--------------------------------------------------------------------------------
/.github/workflows/release-please.yml:
--------------------------------------------------------------------------------
1 | on:
2 | push:
3 | branches:
4 | - main
5 |
6 | name: release-please
7 |
8 | jobs:
9 | release-please:
10 | runs-on: ubuntu-latest
11 |
12 | permissions:
13 | # Write to "contents" is needed to create a release
14 | contents: write
15 | # Write to pull-requests is needed to create and update the release PR
16 | pull-requests: write
17 |
18 | steps:
19 | # Create/update release PR
20 | - uses: googleapis/release-please-action@v4
21 | id: release
22 | with:
23 | release-type: node
24 |
25 | # The logic below handles npm publication. Each step is conditional on a
26 | # release having been created by someone merging the release PR.
27 | - uses: actions/checkout@v4
28 | with:
29 | ref: refs/tags/${{ steps.release.outputs.tag_name }}
30 | persist-credentials: false
31 | if: ${{ steps.release.outputs.release_created }}
32 |
33 | - uses: actions/setup-node@v4
34 | with:
35 | node-version: 22
36 | registry-url: 'https://registry.npmjs.org'
37 | if: ${{ steps.release.outputs.release_created }}
38 |
39 | - run: npm ci
40 | if: ${{ steps.release.outputs.release_created }}
41 |
42 | - run: npm publish
43 | env:
44 | NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}}
45 | if: ${{ steps.release.outputs.release_created }}
46 |
47 | - run: npm pack
48 | if: ${{ steps.release.outputs.release_created }}
49 |
50 | - name: Attach files to release
51 | env:
52 | GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
53 | run: |
54 | gh release upload --clobber "${{ steps.release.outputs.tag_name }}" eme-encryption-scheme-polyfill-*.tgz
55 | if: ${{ steps.release.outputs.release_created }}
56 |
--------------------------------------------------------------------------------
/.github/workflows/sync-labels.yaml:
--------------------------------------------------------------------------------
1 | # Install this in .github/workflows/ to automate label updates
2 | name: Sync Labels
3 |
4 | on:
5 | workflow_dispatch:
6 | # Allows for manual triggering.
7 | inputs:
8 | dry_run:
9 | description: "If true, don't make any actual changes"
10 | required: false
11 | default: false
12 | schedule:
13 | # Run every week on Sunday at 5:42 AM.
14 | - cron: '42 5 * * 0'
15 |
16 | jobs:
17 | sync-labels:
18 | runs-on: ubuntu-latest
19 |
20 | permissions:
21 | # "Write" to Issues to manage labels for the repo
22 | issues: write
23 |
24 | steps:
25 | - name: Checkout code
26 | uses: actions/checkout@v4
27 | with:
28 | repository: shaka-project/shaka-github-tools
29 | persist-credentials: false
30 |
31 | # TODO: revert to micnncim and new release after landing
32 | # https://github.com/micnncim/action-label-syncer/pull/68
33 | - uses: joeyparrish/action-label-syncer@v1.8.0
34 | with:
35 | dry_run: ${{ github.event.inputs.dry_run || false }}
36 | prune: true
37 | manifest: sync-labels/configs/${{ github.repository }}.yaml
38 | repository: ${{ github.repository }}
39 | token: ${{ github.token }}
40 |
--------------------------------------------------------------------------------
/.github/workflows/test.yaml:
--------------------------------------------------------------------------------
1 | name: Test PRs
2 |
3 | on:
4 | pull_request: # Trigger for pull requests.
5 | types: [opened, synchronize, reopened]
6 | workflow_dispatch: # Allows for manual triggering.
7 | inputs:
8 | ref:
9 | description: "The ref to build and test."
10 | required: False
11 |
12 | concurrency:
13 | group: ${{ github.workflow }}-${{ github.event.number || inputs.ref }}
14 | cancel-in-progress: true
15 |
16 | jobs:
17 | test:
18 | name: Test
19 | runs-on: ubuntu-latest
20 | steps:
21 | - name: Checkout code
22 | uses: actions/checkout@v4
23 | with:
24 | ref: ${{ inputs.ref || github.ref }}
25 | persist-credentials: false
26 |
27 | - name: Test
28 | run: |
29 | npm ci
30 | npm test
31 |
--------------------------------------------------------------------------------
/.github/workflows/update-issues.yaml:
--------------------------------------------------------------------------------
1 | # Install this in .github/workflows/ to automate issue maintenance.
2 | name: Update Issues
3 |
4 | on:
5 | workflow_dispatch:
6 | # Allows for manual triggering.
7 | schedule:
8 | # Run every 30 minutes
9 | - cron: '*/30 * * * *'
10 |
11 | jobs:
12 | update-issues:
13 | runs-on: ubuntu-latest
14 |
15 | permissions:
16 | # "Write" to Issues to add labels, milestones, comments, etc.
17 | issues: write
18 | # "Write" to Pull Requests for the same.
19 | pull-requests: write
20 |
21 | steps:
22 | - name: Checkout code
23 | uses: actions/checkout@v4
24 | with:
25 | repository: shaka-project/shaka-github-tools
26 | persist-credentials: false
27 |
28 | - name: Update Issues
29 | env:
30 | # Use SHAKA_BOT_TOKEN if found, otherwise the default GITHUB_TOKEN.
31 | GITHUB_TOKEN: ${{ secrets.SHAKA_BOT_TOKEN || secrets.GITHUB_TOKEN }}
32 | run: |
33 | cd update-issues
34 | npm ci
35 | node main.js
36 |
--------------------------------------------------------------------------------
/.github/workflows/validate-pr-title.yaml:
--------------------------------------------------------------------------------
1 | name: Validate PR Title
2 |
3 | on:
4 | # NOTE: The automated PRs from release-please-action do not seem to trigger
5 | # any of the default PR triggers (opened, synchronize, reopened). So we need
6 | # additional types. This is a good set that makes it easy to trigger the
7 | # workflow manually if needed. This is not neccessary if your release-please
8 | # workflow uses a personal access token (PAT) from Shaka Bot.
9 | pull_request_target:
10 | types:
11 | - opened
12 | - reopened
13 | - edited
14 | - synchronize
15 | - assigned
16 | - labeled
17 | - ready_for_review
18 | - review_requested
19 |
20 | jobs:
21 | main:
22 | name: Validate PR Title
23 | runs-on: ubuntu-latest
24 | steps:
25 | - uses: amannn/action-semantic-pull-request@v5
26 | env:
27 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
28 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | dist/
3 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Changelog
2 |
3 |
4 | ## [2.2.3](https://github.com/shaka-project/eme-encryption-scheme-polyfill/compare/v2.2.2...v2.2.3) (2025-05-12)
5 |
6 |
7 | ### Bug Fixes
8 |
9 | * null encryptionScheme is valid ([#97](https://github.com/shaka-project/eme-encryption-scheme-polyfill/issues/97)) ([3db8fee](https://github.com/shaka-project/eme-encryption-scheme-polyfill/commit/3db8feedbc27a074796cef0361853dd9b9596e58))
10 |
11 | ## [2.2.2](https://github.com/shaka-project/eme-encryption-scheme-polyfill/compare/v2.2.1...v2.2.2) (2025-05-05)
12 |
13 |
14 | ### Bug Fixes
15 |
16 | * Fix detection of encryptionScheme ([#94](https://github.com/shaka-project/eme-encryption-scheme-polyfill/issues/94)) ([04e3ac4](https://github.com/shaka-project/eme-encryption-scheme-polyfill/commit/04e3ac46dbbebc0e7f30536eedd44f9ade0e823a))
17 |
18 | ## [2.2.1](https://github.com/shaka-project/eme-encryption-scheme-polyfill/compare/v2.2.0...v2.2.1) (2025-01-29)
19 |
20 |
21 | ### Bug Fixes
22 |
23 | * Do not check compatibility if MCap configuration is not compatible ([#92](https://github.com/shaka-project/eme-encryption-scheme-polyfill/issues/92)) ([e59e327](https://github.com/shaka-project/eme-encryption-scheme-polyfill/commit/e59e3272f38c534b5ac12352e1a705cb507f213e))
24 |
25 | ## [2.2.0](https://github.com/shaka-project/eme-encryption-scheme-polyfill/compare/v2.1.6...v2.2.0) (2025-01-09)
26 |
27 |
28 | ### Features
29 |
30 | * Add support for huawei wiseplay drm ([#90](https://github.com/shaka-project/eme-encryption-scheme-polyfill/issues/90)) ([7760e58](https://github.com/shaka-project/eme-encryption-scheme-polyfill/commit/7760e58f69fac3fe05ad6efac2b55847351ed6e0))
31 |
32 | ## [2.1.6](https://github.com/shaka-project/eme-encryption-scheme-polyfill/compare/v2.1.5...v2.1.6) (2024-11-21)
33 |
34 |
35 | ### Bug Fixes
36 |
37 | * Fix CBCS support in recent WebOS ([#81](https://github.com/shaka-project/eme-encryption-scheme-polyfill/issues/81)) ([d5ecb15](https://github.com/shaka-project/eme-encryption-scheme-polyfill/commit/d5ecb15259ba6cd23a5b42a63c882ccb29469773))
38 |
39 | ## [2.1.5](https://github.com/shaka-project/eme-encryption-scheme-polyfill/compare/v2.1.4...v2.1.5) (2024-05-21)
40 |
41 |
42 | ### Bug Fixes
43 |
44 | * Fix access to null properties ([#73](https://github.com/shaka-project/eme-encryption-scheme-polyfill/issues/73)) ([339842e](https://github.com/shaka-project/eme-encryption-scheme-polyfill/commit/339842e94372d2f1b5d9605b88b38908fc2a6459))
45 |
46 | ## [2.1.4](https://github.com/shaka-project/eme-encryption-scheme-polyfill/compare/v2.1.3...v2.1.4) (2024-05-16)
47 |
48 |
49 | ### Bug Fixes
50 |
51 | * Fix conflicts with multiple installations ([#71](https://github.com/shaka-project/eme-encryption-scheme-polyfill/issues/71)) ([d74823f](https://github.com/shaka-project/eme-encryption-scheme-polyfill/commit/d74823fe9e537497f1ec858943d9c1c6d152c2c3))
52 |
53 | ## [2.1.3](https://github.com/shaka-project/eme-encryption-scheme-polyfill/compare/v2.1.2...v2.1.3) (2024-05-14)
54 |
55 |
56 | ### Bug Fixes
57 |
58 | * **demo:** Log demo errors to the console ([#68](https://github.com/shaka-project/eme-encryption-scheme-polyfill/issues/68)) ([ccfb179](https://github.com/shaka-project/eme-encryption-scheme-polyfill/commit/ccfb1793ca80594a368cb669b97fa3ce0c50a09c))
59 | * **demo:** Upgrade UI combo box component ([#67](https://github.com/shaka-project/eme-encryption-scheme-polyfill/issues/67)) ([0d51ba6](https://github.com/shaka-project/eme-encryption-scheme-polyfill/commit/0d51ba6b96ccadf556d8f6ef90501906258d3186))
60 | * Populate requested scheme into output, not default scheme ([#69](https://github.com/shaka-project/eme-encryption-scheme-polyfill/issues/69)) ([aa79c72](https://github.com/shaka-project/eme-encryption-scheme-polyfill/commit/aa79c72fdab050d98c682fee2b0b1d2bcdeb47d6))
61 |
62 | ## [2.1.2](https://github.com/shaka-project/eme-encryption-scheme-polyfill/compare/v2.1.1...v2.1.2) (2024-05-07)
63 |
64 |
65 | ### Bug Fixes
66 |
67 | * Fix CBCS support in some platforms ([#63](https://github.com/shaka-project/eme-encryption-scheme-polyfill/issues/63)) ([3978d61](https://github.com/shaka-project/eme-encryption-scheme-polyfill/commit/3978d619eb03534d89651a0cb11be8a9afad3387)), closes [#62](https://github.com/shaka-project/eme-encryption-scheme-polyfill/issues/62)
68 | * Use cbcs as default scheme for Safari ([#64](https://github.com/shaka-project/eme-encryption-scheme-polyfill/issues/64)) ([5316552](https://github.com/shaka-project/eme-encryption-scheme-polyfill/commit/53165526cd0297a987c7802bb2d7b190b7eb0c71))
69 |
70 | ## [2.1.1](https://github.com/shaka-project/eme-encryption-scheme-polyfill/compare/v2.1.0...v2.1.1) (2022-08-10)
71 |
72 |
73 | ### Bug Fixes
74 |
75 | * Fix ES6 transpilation ([#49](https://github.com/shaka-project/eme-encryption-scheme-polyfill/issues/49)) ([b170e12](https://github.com/shaka-project/eme-encryption-scheme-polyfill/commit/b170e12db57f772470eb98dbbb5327b1a03caabc)), closes [#48](https://github.com/shaka-project/eme-encryption-scheme-polyfill/issues/48)
76 |
77 | ## [2.1.0](https://github.com/shaka-project/eme-encryption-scheme-polyfill/compare/v2.0.5...v2.1.0) (2022-07-22)
78 |
79 |
80 | ### Features
81 |
82 | * Add support for Chromecast version of PlayReady ([#45](https://github.com/shaka-project/eme-encryption-scheme-polyfill/issues/45)) ([180f697](https://github.com/shaka-project/eme-encryption-scheme-polyfill/commit/180f697d5d65527360c9d9096770f7eb74152d62))
83 |
84 | ## [2.0.5](https://github.com/shaka-project/eme-encryption-scheme-polyfill/compare/v2.0.4...v2.0.5) (2022-06-07)
85 |
86 |
87 | ### Bug Fixes
88 |
89 | * Avoid duplicate calls to decodingInfo() ([#43](https://github.com/shaka-project/eme-encryption-scheme-polyfill/issues/43)) ([fafd1dd](https://github.com/shaka-project/eme-encryption-scheme-polyfill/commit/fafd1dd228e60f630274c77e28ed9ac7742d31cd))
90 |
91 | ### [2.0.4](https://github.com/shaka-project/eme-encryption-scheme-polyfill/compare/v2.0.3...v2.0.4) (2022-03-04)
92 |
93 |
94 | ### Bug Fixes
95 |
96 | * **deps:** Update all dependencies ([#32](https://github.com/shaka-project/eme-encryption-scheme-polyfill/issues/32)) ([761dece](https://github.com/shaka-project/eme-encryption-scheme-polyfill/commit/761deceb36e28063ebf25077af10fea9a848901e))
97 |
98 | ## 2.0.3 (2021-04-19)
99 |
100 | Bugfixes:
101 | - Fix MCap polyfill for browsers that support MCap but not the
102 | encryption-related parts of the MCap API.
103 |
104 |
105 | ## 2.0.2 (2021-02-05)
106 |
107 | Bugfixes:
108 | - Fix infinite recursion when the MCap part of the polyfill is installed
109 | twice.
110 | - Fix exception when MCap returns a supported==false on encrypted content.
111 |
112 |
113 | ## 2.0.1 (2020-02-21)
114 |
115 | Bugfixes:
116 | - Fix exception thrown on some legacy Edge versions
117 |
118 |
119 | ## 2.0.0 (2019-12-12)
120 |
121 | Features:
122 | - Added support for polyfilling MediaCapabilities, too
123 | - https://github.com/w3c/media-capabilities/issues/100
124 |
125 |
126 | ## 1.0.3 (2019-12-05)
127 |
128 | Bugfixes:
129 | - Update cbcs-recommended to cbcs-1-9 to keep up with spec changes
130 |
131 |
132 | ## 1.0.2 (2019-12-02)
133 |
134 | Bugfixes:
135 | - Fix infinite recursion when the polyfill is installed twice.
136 |
137 |
138 | ## 1.0.1 (2019-11-22)
139 |
140 | Bugfixes:
141 | - Fix RequireJS support
142 | - Workaround babel translation bug that resulted in undefined return value
143 | - Fix errors in Closure Compiler with strictest settings
144 |
145 | Features:
146 | - Added a demo / manual testing page
147 | - https://shaka-project.github.io/eme-encryption-scheme-polyfill/demo/
148 |
149 |
150 | ## 1.0.0 (2019-11-18)
151 |
152 | First public release.
153 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Contributor Covenant Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | We as members, contributors, and leaders pledge to make participation in our
6 | community a harassment-free experience for everyone, regardless of age, body
7 | size, visible or invisible disability, ethnicity, sex characteristics, gender
8 | identity and expression, level of experience, education, socio-economic status,
9 | nationality, personal appearance, race, caste, color, religion, or sexual
10 | identity and orientation.
11 |
12 | We pledge to act and interact in ways that contribute to an open, welcoming,
13 | diverse, inclusive, and healthy community.
14 |
15 | ## Our Standards
16 |
17 | Examples of behavior that contributes to a positive environment for our
18 | community include:
19 |
20 | * Demonstrating empathy and kindness toward other people
21 | * Being respectful of differing opinions, viewpoints, and experiences
22 | * Giving and gracefully accepting constructive feedback
23 | * Accepting responsibility and apologizing to those affected by our mistakes,
24 | and learning from the experience
25 | * Focusing on what is best not just for us as individuals, but for the overall
26 | community
27 |
28 | Examples of unacceptable behavior include:
29 |
30 | * The use of sexualized language or imagery, and sexual attention or advances of
31 | any kind
32 | * Trolling, insulting or derogatory comments, and personal or political attacks
33 | * Public or private harassment
34 | * Publishing others' private information, such as a physical or email address,
35 | without their explicit permission
36 | * Other conduct which could reasonably be considered inappropriate in a
37 | professional setting
38 |
39 | ## Enforcement Responsibilities
40 |
41 | Community leaders are responsible for clarifying and enforcing our standards of
42 | acceptable behavior and will take appropriate and fair corrective action in
43 | response to any behavior that they deem inappropriate, threatening, offensive,
44 | or harmful.
45 |
46 | Community leaders have the right and responsibility to remove, edit, or reject
47 | comments, commits, code, wiki edits, issues, and other contributions that are
48 | not aligned to this Code of Conduct, and will communicate reasons for moderation
49 | decisions when appropriate.
50 |
51 | ## Scope
52 |
53 | This Code of Conduct applies within all community spaces, and also applies when
54 | an individual is officially representing the community in public spaces.
55 | Examples of representing our community include using an official email address,
56 | posting via an official social media account, or acting as an appointed
57 | representative at an online or offline event.
58 |
59 | ## Enforcement
60 |
61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be
62 | reported to the community leaders responsible for enforcement at
63 | *shaka-player-maintainers@googlegroups.com*. If for any reason, you are
64 | uncomfortable reaching out to the community leaders, please email
65 | *opensource@google.com*.
66 | All complaints will be reviewed and investigated promptly and fairly.
67 |
68 | All community leaders are obligated to respect the privacy and security of the
69 | reporter of any incident.
70 |
71 | ## Enforcement Guidelines
72 |
73 | Community leaders will follow these Community Impact Guidelines in determining
74 | the consequences for any action they deem in violation of this Code of Conduct:
75 |
76 | ### 1. Correction
77 |
78 | **Community Impact**: Use of inappropriate language or other behavior deemed
79 | unprofessional or unwelcome in the community.
80 |
81 | **Consequence**: A written warning from community leaders, providing
82 | clarity around the nature of the violation and an explanation of why the
83 | behavior was inappropriate. A public apology may be requested.
84 |
85 | ### 2. Warning
86 |
87 | **Community Impact**: A violation through a single incident or series of
88 | actions.
89 |
90 | **Consequence**: A warning with consequences for continued behavior. No
91 | interaction with the people involved, including unsolicited interaction with
92 | those enforcing the Code of Conduct, for a specified period of time. This
93 | includes avoiding interactions in community spaces as well as external channels
94 | like social media. Violating these terms may lead to a temporary or permanent
95 | ban.
96 |
97 | ### 3. Temporary Ban
98 |
99 | **Community Impact**: A serious violation of community standards, including
100 | sustained inappropriate behavior.
101 |
102 | **Consequence**: A temporary ban from any sort of interaction or public
103 | communication with the community for a specified period of time. No public or
104 | private interaction with the people involved, including unsolicited interaction
105 | with those enforcing the Code of Conduct, is allowed during this period.
106 | Violating these terms may lead to a permanent ban.
107 |
108 | ### 4. Permanent Ban
109 |
110 | **Community Impact**: Demonstrating a pattern of violation of community
111 | standards, including sustained inappropriate behavior, harassment of an
112 | individual, or aggression toward or disparagement of classes of individuals.
113 |
114 | **Consequence**: A permanent ban from any sort of public interaction within the
115 | community.
116 |
117 | ## Attribution
118 |
119 | This Code of Conduct is adapted from the [Contributor Covenant][homepage],
120 | version 2.1, available at
121 | [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
122 |
123 | Community Impact Guidelines were inspired by
124 | [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
125 |
126 | For answers to common questions about this code of conduct, see the FAQ at
127 | [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
128 | [https://www.contributor-covenant.org/translations][translations].
129 |
130 | [homepage]: https://www.contributor-covenant.org
131 | [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
132 | [Mozilla CoC]: https://github.com/mozilla/diversity
133 | [FAQ]: https://www.contributor-covenant.org/faq
134 | [translations]: https://www.contributor-covenant.org/translations
135 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # How to Contribute
2 |
3 | We'd love to accept your patches and contributions to this project. There are
4 | just a few small guidelines you need to follow.
5 |
6 | ## Contributor License Agreement
7 |
8 | Contributions to this project must be accompanied by a Contributor License
9 | Agreement. You (or your employer) retain the copyright to your contribution;
10 | this simply gives us permission to use and redistribute your contributions as
11 | part of the project. Head over to to see
12 | your current agreements on file or to sign a new one.
13 |
14 | You generally only need to submit a CLA once, so if you've already submitted one
15 | (even if it was for a different project), you probably don't need to do it
16 | again.
17 |
18 | ## Code reviews
19 |
20 | All submissions, including submissions by project members, require review. We
21 | use GitHub pull requests for this purpose. Consult
22 | [GitHub Help](https://help.github.com/articles/about-pull-requests/) for more
23 | information on using pull requests.
24 |
25 | ## Community Guidelines
26 |
27 | This project follows [Google's Open Source Community
28 | Guidelines](https://opensource.google/conduct/).
29 |
30 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright [yyyy] [name of copyright owner]
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
203 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # EME & MediaCapabilities Encryption Scheme Polyfill
2 |
3 | A polyfill to add support for EncryptionScheme queries in EME and
4 | MediaCapabilities.
5 |
6 | - https://wicg.github.io/encrypted-media-encryption-scheme/
7 | - https://shaka-project.github.io/eme-encryption-scheme-polyfill/demo/
8 | - https://github.com/WICG/encrypted-media-encryption-scheme/issues/13
9 | - https://github.com/w3c/media-capabilities/issues/100
10 |
11 | Because this polyfill can't know what schemes the UA or CDM actually support,
12 | it assumes support for the historically-supported schemes of each well-known
13 | key system.
14 |
15 | In source form (`index.js`), this is compatible with the Closure Compiler and
16 | the CommonJS module format. It can also be directly included via a script tag.
17 |
18 | The minified bundle (`dist/eme-encryption-scheme-polyfill.js`) is a standalone
19 | module compatible with the CommonJS and AMD module formats, and can also be
20 | directly included via a script tag.
21 |
22 | The v2.0.3 build is about 5.3kB uncompressed, and gzips to about 1.7kB.
23 |
24 | To avoid the possibility of extra user prompts, this will shim EME & MC so long
25 | as they exist, without checking support for `encryptionScheme` upfront. The
26 | support check will happen on-demand the first time EME/MC are used.
27 |
28 |
29 | ## Usage
30 |
31 | ```sh
32 | npm install eme-encryption-scheme-polyfill
33 | ```
34 |
35 | ```html
36 |
37 | ```
38 |
39 | ```js
40 | // Install both EME & MC polyfills at once:
41 | EncryptionSchemePolyfills.install();
42 |
43 | // Install each one separately (unminified source only):
44 | EmeEncryptionSchemePolyfill.install();
45 | McEncryptionSchemePolyfill.install();
46 | ```
47 |
--------------------------------------------------------------------------------
/SECURITY.md:
--------------------------------------------------------------------------------
1 | # Security Policy
2 |
3 | ## Supported Versions
4 |
5 | * This repository does not currently maintain release branches. **Only the latest release is supported.**
6 |
7 | * If a security issue is identified in a current release, the fix will trigger a new release from `main`.
8 |
9 | * If a security issue is identified in any release, we will disclose the issue and advise everyone to upgrade to the latest release.
10 |
11 |
12 | ## Reporting a Vulnerability
13 |
14 | Per Google policy, please use https://g.co/vulnz to report security vulnerabilities. Google uses this for intake and triage. For valid issues, we will do coordination and disclosure here on GitHub (including using a GitHub Security Advisory when necessary).
15 |
16 | The Google Security Team will process your report within a day, and respond within a week (although it will depend on the severity of your report).
17 |
18 |
19 | ## Remediation Actions
20 |
21 | * A GitHub issue will be created with the `type: vulnerability` label to coordinate a response. After remediation, we will also use this issue to disclose any details we withheld between receiving the private report and resolving the issue.
22 |
23 | * A GitHub Security Advisory may be created, if appropriate. For example, this would be done if the issue impacts users or dependent projects. This might be skipped for other issues, such as CI workflow vulnerabilities.
24 |
25 | * Vulnerabilities in NPM modules will be reported to NPM so that they show up in `npm audit`.
26 |
27 |
28 |
--------------------------------------------------------------------------------
/closure-compiler-check/goog-stub.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @license
3 | * Copyright 2019 Google LLC
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * https://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | /** @externs */
19 |
20 | // Just to satisfy the compiler while doing a compilation check.
21 | // We don't use the Closure Library, but the compiler expects it.
22 | const goog = {};
23 |
--------------------------------------------------------------------------------
/demo/index.html:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
43 | Choose parameters like key system, encryption scheme, and media types,
44 | then click one of the "run" buttons to see the results of the query with
45 | the polyfill.
46 |
47 |
48 |
49 |
50 |
51 |
com.widevine.alpha
52 |
com.microsoft.playready
53 |
com.apple.fps.1_0
54 |
55 |
56 |
57 |
58 |
59 |
60 |
cenc
61 |
cbcs
62 |
cbcs-1-9
63 |
64 |
65 |
66 |
67 |
68 |
69 |
audio/mp4; codecs="mp4a.40.2"
70 |
audio/mp4; codecs="opus"
71 |
audio/webm; codecs="vorbis"
72 |
audio/webm; codecs="opus"
73 |
74 |
75 |
76 |
77 |
78 |
79 |
video/mp4; codecs="avc1.640028"
80 |
video/mp4; codecs="hev1.1.6.L93.B0"
81 |
video/mp4; codecs="vp09.00.10.08"
82 |
video/mp4; codecs="av01.0.00M.08"
83 |
video/webm; codecs="vp8"
84 |
video/webm; codecs="vp09.00.10.08"
85 |
video/webm; codecs="av01.0.00M.08"
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
Test loading methods
103 |
104 | Here we load the polyfill with each supported loading method using
105 | iframes. Each iframe will show the success or failure of the load. This
106 | does not test the functionality of the polyfill beyond loading.
107 |
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 |
--------------------------------------------------------------------------------
/demo/load-tests/load-as-es-module.html:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
19 |
20 |
21 |
22 | EME Encryption Scheme Polyfill - load as ES module
23 |
24 |
30 |
31 |
32 |
33 |
34 |
--------------------------------------------------------------------------------
/demo/load-tests/load-raw-source-with-script-tag.html:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
19 |
20 |
21 |
22 | EME Encryption Scheme Polyfill - load raw source with script tag
23 |
24 |
30 |
31 |
32 |
33 |
34 |
--------------------------------------------------------------------------------
/demo/load-tests/load-with-requirejs.html:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
19 |
20 |
21 |
22 | EME Encryption Scheme Polyfill - load with RequireJS
23 |
24 |
36 |
37 |
38 |
39 |
40 |
--------------------------------------------------------------------------------
/demo/load-tests/load-with-script-tag.html:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
19 |
20 |
21 |
22 | EME Encryption Scheme Polyfill - load with script tag
23 |
24 |
30 |
31 |
32 |
33 |
34 |
--------------------------------------------------------------------------------
/demo/load-tests/test-load.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @license
3 | * Copyright 2019 Google LLC
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * https://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | function checkDefinition(polyfill) {
19 | console.debug('Polyfill:', polyfill, polyfill && polyfill.install);
20 | const polyfillIsCorrectlyDefined = !!polyfill && !!polyfill.install;
21 | return polyfillIsCorrectlyDefined;
22 | }
23 |
24 | document.addEventListener('DOMContentLoaded', async () => {
25 | const title = document.title.split('-')[1];
26 |
27 | if (window.parent != window) {
28 | const popOutButton = document.createElement('button');
29 | popOutButton.textContent = 'pop out';
30 | popOutButton.style.marginRight = '1em';
31 | popOutButton.addEventListener('click', () => {
32 | window.parent.location = location.href;
33 | });
34 | document.body.appendChild(popOutButton);
35 | }
36 |
37 | const titleDiv = document.createElement('span');
38 | titleDiv.textContent = `Testing ${title}`;
39 | document.body.appendChild(titleDiv);
40 |
41 | const status = document.createElement('span');
42 | titleDiv.appendChild(status);
43 |
44 | status.textContent = '...';
45 |
46 | try {
47 | const okay = await testLoader() ? 'OK' : 'FAILED!';
48 | status.textContent = `: ${okay}`;
49 | } catch (error) {
50 | status.textContent = `: Error "${error.message}"`;
51 | }
52 | });
53 |
--------------------------------------------------------------------------------
/demo/push-to-github-pages.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # Copyright 2019 Google LLC
4 | #
5 | # Licensed under the Apache License, Version 2.0 (the "License");
6 | # you may not use this file except in compliance with the License.
7 | # You may obtain a copy of the License at
8 | #
9 | # https://www.apache.org/licenses/LICENSE-2.0
10 | #
11 | # Unless required by applicable law or agreed to in writing, software
12 | # distributed under the License is distributed on an "AS IS" BASIS,
13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | # See the License for the specific language governing permissions and
15 | # limitations under the License.
16 |
17 | set -e # Exit with nonzero exit code if anything fails
18 | set -x # Show the commands being run
19 |
20 | REPO=git@github.com:shaka-project/eme-encryption-scheme-polyfill.git
21 | SOURCE_BRANCH=main
22 | TARGET_BRANCH=gh-pages
23 |
24 |
25 | # Check out and build the code.
26 | rm -rf build
27 | git clone "$REPO" build
28 |
29 | pushd build
30 | git checkout "$SOURCE_BRANCH"
31 | SHA=$(git rev-parse --verify HEAD)
32 | npm install
33 | npm run-script prepublishOnly
34 | popd
35 |
36 |
37 | # Check out and update the gh-pages branch.
38 | rm -rf gh-pages
39 | git clone "$REPO" gh-pages
40 |
41 | pushd gh-pages
42 | git checkout "$TARGET_BRANCH"
43 | git rm -rf *
44 | mv ../build/* .
45 | rm -rf node_modules/
46 | git add *
47 | git commit -m "Deploy to GitHub Pages: $SHA" --no-verify
48 | git push "$REPO" "$TARGET_BRANCH"
49 | popd
50 |
51 |
52 | # Clean up.
53 | rm -rf build
54 | rm -rf gh-pages
55 |
--------------------------------------------------------------------------------
/demo/query.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @license
3 | * Copyright 2019 Google LLC
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * https://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | document.addEventListener('DOMContentLoaded', () => {
19 | const formatObjectToString = (obj) => JSON.stringify(obj, null, 2);
20 |
21 | window.emeRun.addEventListener('click', async () => {
22 | // Pull contents of query form.
23 | const keySystem = window.keySystem.input.value;
24 | // If encryptionScheme is blank, default to null.
25 | const encryptionScheme = window.encryptionScheme.input.value || null;
26 | const audio = window.audio.input.value;
27 | const video = window.video.input.value;
28 |
29 | const config = {};
30 |
31 | // As of Safari 13, Apple only responds to this non-standard init data type.
32 | if (keySystem.startsWith('com.apple')) {
33 | config.initDataTypes = ['sinf'];
34 | }
35 |
36 | if (audio) {
37 | config.audioCapabilities = [{
38 | contentType: audio,
39 | encryptionScheme,
40 | }];
41 | }
42 |
43 | if (video) {
44 | config.videoCapabilities = [{
45 | contentType: video,
46 | encryptionScheme,
47 | }];
48 | }
49 |
50 | try {
51 | const mksa =
52 | await navigator.requestMediaKeySystemAccess(keySystem, [config]);
53 | window.results.textContent =
54 | formatObjectToString(mksa.getConfiguration());
55 | } catch (error) {
56 | console.log(error);
57 | window.results.textContent = formatObjectToString({error: error.message});
58 | }
59 | }); // emeRun click listener
60 |
61 | window.mcRun.addEventListener('click', async () => {
62 | // Pull contents of query form.
63 | const keySystem = window.keySystem.input.value;
64 | // If encryptionScheme is blank, default to null.
65 | const encryptionScheme = window.encryptionScheme.input.value || null;
66 | const audio = window.audio.input.value;
67 | const video = window.video.input.value;
68 |
69 | const config = {
70 | type: 'media-source',
71 | };
72 |
73 | if (keySystem) {
74 | config.keySystemConfiguration = {
75 | keySystem,
76 | };
77 | }
78 |
79 | if (audio) {
80 | config.audio = {
81 | contentType: audio,
82 | };
83 |
84 | if (keySystem) {
85 | config.keySystemConfiguration.audio = {
86 | encryptionScheme,
87 | };
88 | }
89 | }
90 |
91 | if (video) {
92 | config.video = {
93 | contentType: video,
94 | width: 640,
95 | height: 480,
96 | bitrate: 1,
97 | framerate: 24,
98 | };
99 |
100 | if (keySystem) {
101 | config.keySystemConfiguration.video = {
102 | encryptionScheme,
103 | };
104 | }
105 | }
106 |
107 | try {
108 | const result = await navigator.mediaCapabilities.decodingInfo(config);
109 | window.results.textContent = formatObjectToString(result);
110 |
111 | const mksa = result.keySystemAccess;
112 | if (mksa) {
113 | window.results.textContent += '\n' +
114 | formatObjectToString(mksa.getConfiguration());
115 | }
116 | } catch (error) {
117 | console.log(error);
118 | window.results.textContent = formatObjectToString({error: error.message});
119 | }
120 | }); // mcRun click listener
121 | }); // DOMContentLoaded listener
122 |
--------------------------------------------------------------------------------
/demo/style.css:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2019 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * https://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | h1 {
18 | font-size: 200%;
19 | }
20 |
21 | h2 {
22 | font-size: 160%;
23 | }
24 |
25 | div.description {
26 | font-size: 120%;
27 | font-weight: normal;
28 | }
29 |
30 | div.divider {
31 | height: 4em;
32 | }
33 |
34 | elix-auto-complete-combo-box {
35 | width: 100%;
36 | max-width: 300px;
37 | }
38 |
39 | /* Work around a bug where elix-auto-complete-combo-boxes render underneath each
40 | * other in Safari. We're using explicit z-indexes to work around this. */
41 | #keySystem { z-index: 9; }
42 | #encryptionScheme { z-index: 8; }
43 | #audio { z-index: 7; }
44 | #video { z-index: 6; }
45 |
46 | button {
47 | font-size: 150%;
48 | margin: 0.5em;
49 | background-color: white;
50 | }
51 |
52 | #results {
53 | font-family: monospace;
54 | white-space: pre;
55 | }
56 |
57 | iframe {
58 | width: 100%;
59 | height: 2em;
60 | border-width: 1px;
61 | }
62 |
--------------------------------------------------------------------------------
/index.html:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
19 |
20 |
21 |
22 |
23 | You should be automatically redirected to the demo.
24 | If not, please click here.
25 |
26 |
27 |
--------------------------------------------------------------------------------
/index.js:
--------------------------------------------------------------------------------
1 | /*!
2 | * @license
3 | * EME Encryption Scheme Polyfill
4 | * Copyright 2019 Google LLC
5 | * SPDX-License-Identifier: Apache-2.0
6 | */
7 | // This special header is retained in minified bundle, and only adds ~120 bytes.
8 |
9 | /**
10 | * A polyfill to add support for EncryptionScheme queries in EME.
11 | *
12 | * Because this polyfill can't know what schemes the UA or CDM actually support,
13 | * it assumes support for the historically-supported schemes of each well-known
14 | * key system.
15 | *
16 | * In source form, this is compatible with the Closure Compiler, CommonJS, and
17 | * AMD module formats. It can also be directly included via a script tag.
18 | *
19 | * The minified bundle is a standalone module compatible with the CommonJS and
20 | * AMD module formats, and can also be directly included via a script tag.
21 | *
22 | * @see https://wicg.github.io/encrypted-media-encryption-scheme/
23 | * @see https://github.com/w3c/encrypted-media/pull/457
24 | * @export
25 | */
26 | class EmeEncryptionSchemePolyfill {
27 | /**
28 | * Installs the polyfill. To avoid the possibility of extra user prompts,
29 | * this will shim EME so long as it exists, without checking support for
30 | * encryptionScheme upfront. The support check will happen on-demand the
31 | * first time EME is used.
32 | *
33 | * @export
34 | */
35 | static install() {
36 | if (EmeEncryptionSchemePolyfill.originalRMKSA_ ||
37 | navigator['emeEncryptionSchemePolyfilled']) {
38 | console.debug('EmeEncryptionSchemePolyfill: Already installed.');
39 | return;
40 | }
41 | if (!navigator.requestMediaKeySystemAccess ||
42 | !MediaKeySystemAccess.prototype.getConfiguration) {
43 | console.debug('EmeEncryptionSchemePolyfill: EME not found');
44 | // No EME.
45 | return;
46 | }
47 |
48 | // Save the original.
49 | EmeEncryptionSchemePolyfill.originalRMKSA_ =
50 | navigator.requestMediaKeySystemAccess;
51 |
52 | // Patch in a method which will check for support on the first call.
53 | console.debug('EmeEncryptionSchemePolyfill: ' +
54 | 'Waiting to detect encryptionScheme support.');
55 | navigator.requestMediaKeySystemAccess =
56 | EmeEncryptionSchemePolyfill.probeRMKSA_;
57 |
58 | // Mark EME as polyfilled. This keeps us from running into conflicts
59 | // between multiple versions of this (compiled Shaka lib vs
60 | // uncompiled source).
61 | navigator['emeEncryptionSchemePolyfilled'] = true;
62 | }
63 |
64 | /**
65 | * A shim for navigator.requestMediaKeySystemAccess to check for
66 | * encryptionScheme support. Only used until we know if the browser has
67 | * native support for the encryptionScheme field.
68 | *
69 | * @this {Navigator}
70 | * @param {string} keySystem The key system ID.
71 | * @param {!Array.} supportedConfigurations An
72 | * array of supported configurations the application can use.
73 | * @return {!Promise.} A Promise to a
74 | * MediaKeySystemAccess instance.
75 | * @private
76 | */
77 | static async probeRMKSA_(keySystem, supportedConfigurations) {
78 | console.assert(this == navigator,
79 | 'bad "this" for requestMediaKeySystemAccess');
80 |
81 | // Call the original version. If the call succeeds, we look at the result
82 | // to decide if the encryptionScheme field is supported or not.
83 | const mediaKeySystemAccess =
84 | await EmeEncryptionSchemePolyfill.originalRMKSA_.call(
85 | this, keySystem, supportedConfigurations);
86 |
87 | if (hasEncryptionScheme(mediaKeySystemAccess)) {
88 | // The browser supports the encryptionScheme field!
89 | // No need for a patch. Revert back to the original implementation.
90 | console.debug('EmeEncryptionSchemePolyfill: ' +
91 | 'Native encryptionScheme support found.');
92 | // eslint-disable-next-line require-atomic-updates
93 | navigator.requestMediaKeySystemAccess =
94 | EmeEncryptionSchemePolyfill.originalRMKSA_;
95 | // Return the results, which are completely valid.
96 | return mediaKeySystemAccess;
97 | }
98 |
99 | // If we land here, the browser does _not_ support the encryptionScheme
100 | // field. So we install another patch to check the encryptionScheme field
101 | // in future calls.
102 | console.debug('EmeEncryptionSchemePolyfill: ' +
103 | 'No native encryptionScheme support found. '+
104 | 'Patching encryptionScheme support.');
105 | // eslint-disable-next-line require-atomic-updates
106 | navigator.requestMediaKeySystemAccess =
107 | EmeEncryptionSchemePolyfill.polyfillRMKSA_;
108 |
109 | // The results we have may not be valid. Run the query again through our
110 | // polyfill.
111 | return EmeEncryptionSchemePolyfill.polyfillRMKSA_.call(
112 | this, keySystem, supportedConfigurations);
113 | }
114 |
115 | /**
116 | * A polyfill for navigator.requestMediaKeySystemAccess to handle the
117 | * encryptionScheme field in browsers that don't support it. It uses the
118 | * user-agent string to guess what encryption schemes are supported, then
119 | * those guesses are used to filter videoCapabilities and audioCapabilities
120 | * and reject unsupported schemes.
121 | *
122 | * @this {Navigator}
123 | * @param {string} keySystem The key system ID.
124 | * @param {!Array.} supportedConfigurations An
125 | * array of supported configurations the application can use.
126 | * @return {!Promise.} A Promise to a
127 | * MediaKeySystemAccess instance.
128 | * @private
129 | */
130 | static async polyfillRMKSA_(keySystem, supportedConfigurations) {
131 | console.assert(this == navigator,
132 | 'bad "this" for requestMediaKeySystemAccess');
133 |
134 | const supportedScheme = guessSupportedScheme(keySystem);
135 |
136 | // Filter the application's configurations based on our guess of what
137 | // encryption scheme is supported.
138 | const filteredSupportedConfigurations = [];
139 | for (const configuration of supportedConfigurations) {
140 | const filteredVideoCapabilities =
141 | EmeEncryptionSchemePolyfill.filterCapabilities_(
142 | configuration.videoCapabilities, supportedScheme);
143 | const filteredAudioCapabilities =
144 | EmeEncryptionSchemePolyfill.filterCapabilities_(
145 | configuration.audioCapabilities, supportedScheme);
146 |
147 | if (configuration.videoCapabilities &&
148 | configuration.videoCapabilities.length &&
149 | !filteredVideoCapabilities.length) {
150 | // We eliminated all of the video capabilities, so this configuration
151 | // is unusable.
152 | } else if (configuration.audioCapabilities &&
153 | configuration.audioCapabilities.length &&
154 | !filteredAudioCapabilities.length) {
155 | // We eliminated all of the audio capabilities, so this configuration
156 | // is unusable.
157 | } else {
158 | // Recreate a clone of the configuration and modify that. This way, we
159 | // don't modify the application-provided config objects.
160 | /** @type {!MediaKeySystemConfiguration} */
161 | const clonedConfiguration = Object.assign({}, configuration);
162 | clonedConfiguration.videoCapabilities = filteredVideoCapabilities;
163 | clonedConfiguration.audioCapabilities = filteredAudioCapabilities;
164 | filteredSupportedConfigurations.push(clonedConfiguration);
165 | }
166 | }
167 |
168 | if (!filteredSupportedConfigurations.length) {
169 | // None of the application's configurations passed our encryptionScheme
170 | // filters, so this request fails.
171 |
172 | // As spec'd, this should be a DOMException, but there is not a public
173 | // constructor for this in all browsers. This should be close enough for
174 | // most applications.
175 | const unsupportedError = new Error(
176 | 'Unsupported keySystem or supportedConfigurations.');
177 | unsupportedError.name = 'NotSupportedError';
178 | unsupportedError['code'] = DOMException.NOT_SUPPORTED_ERR;
179 | throw unsupportedError;
180 | }
181 |
182 | // At this point, we have some filtered configurations that we think could
183 | // work. Pass this subset to the native version of RMKSA.
184 | const mediaKeySystemAccess =
185 | await EmeEncryptionSchemePolyfill.originalRMKSA_.call(
186 | this, keySystem, filteredSupportedConfigurations);
187 |
188 | // Wrap the MKSA object in ours to provide the missing field in the
189 | // returned configuration.
190 | let videoScheme = null;
191 | let audioScheme = null;
192 | if (filteredSupportedConfigurations[0]) {
193 | if (filteredSupportedConfigurations[0].videoCapabilities) {
194 | videoScheme = filteredSupportedConfigurations[0]
195 | .videoCapabilities[0].encryptionScheme;
196 | }
197 | if (filteredSupportedConfigurations[0].audioCapabilities) {
198 | audioScheme = filteredSupportedConfigurations[0]
199 | .audioCapabilities[0].encryptionScheme;
200 | }
201 | }
202 | return new EmeEncryptionSchemePolyfillMediaKeySystemAccess(
203 | mediaKeySystemAccess, videoScheme, audioScheme);
204 | }
205 |
206 | /**
207 | * Filters out capabilities that don't match the supported encryption scheme.
208 | *
209 | * @param {!Array.|undefined} capabilities
210 | * An array of capabilities, or null or undefined.
211 | * @param {?string} supportedScheme The encryption scheme that we think is
212 | * supported by the key system.
213 | * @return {!Array.|undefined} A filtered
214 | * array of capabilities based on |supportedScheme|. May be undefined if
215 | * the input was undefined.
216 | * @private
217 | */
218 | static filterCapabilities_(capabilities, supportedScheme) {
219 | if (!capabilities) {
220 | return capabilities;
221 | }
222 |
223 | return capabilities.filter((capability) => {
224 | return checkSupportedScheme(
225 | capability['encryptionScheme'], supportedScheme);
226 | });
227 | }
228 | }
229 |
230 | /**
231 | * A polyfill to add support for EncryptionScheme queries in MediaCapabilities.
232 | *
233 | * Because this polyfill can't know what schemes the UA or CDM actually support,
234 | * it assumes support for the historically-supported schemes of each well-known
235 | * key system.
236 | *
237 | * In source form, this is compatible with the Closure Compiler, CommonJS, and
238 | * AMD module formats. It can also be directly included via a script tag.
239 | *
240 | * The minified bundle is a standalone module compatible with the CommonJS and
241 | * AMD module formats, and can also be directly included via a script tag.
242 | *
243 | * @see https://wicg.github.io/encrypted-media-encryption-scheme/
244 | * @see https://github.com/w3c/encrypted-media/pull/457
245 | * @export
246 | */
247 | class McEncryptionSchemePolyfill {
248 | /**
249 | * Installs the polyfill. To avoid the possibility of extra user prompts,
250 | * this will shim MC so long as it exists, without checking support for
251 | * encryptionScheme upfront. The support check will happen on-demand the
252 | * first time MC is used.
253 | *
254 | * @export
255 | */
256 | static install() {
257 | if (McEncryptionSchemePolyfill.originalDecodingInfo_ ||
258 | navigator['mediaCapabilitiesEncryptionSchemePolyfilled']) {
259 | console.debug('McEncryptionSchemePolyfill: Already installed.');
260 | return;
261 | }
262 | if (!navigator.mediaCapabilities) {
263 | console.debug('McEncryptionSchemePolyfill: MediaCapabilities not found');
264 | // No MediaCapabilities.
265 | return;
266 | }
267 |
268 | // Save the original.
269 | McEncryptionSchemePolyfill.originalDecodingInfo_ =
270 | navigator.mediaCapabilities.decodingInfo;
271 |
272 | // Patch in a method which will check for support on the first call.
273 | console.debug('McEncryptionSchemePolyfill: ' +
274 | 'Waiting to detect encryptionScheme support.');
275 | navigator.mediaCapabilities.decodingInfo =
276 | McEncryptionSchemePolyfill.probeDecodingInfo_;
277 |
278 | // Mark MediaCapabilities as polyfilled. This keeps us from running into
279 | // conflicts between multiple versions of this (compiled Shaka lib vs
280 | // uncompiled source).
281 | navigator['mediaCapabilitiesEncryptionSchemePolyfilled'] = true;
282 | }
283 |
284 | /**
285 | * A shim for mediaCapabilities.decodingInfo to check for encryptionScheme
286 | * support. Only used until we know if the browser has native support for the
287 | * encryptionScheme field.
288 | *
289 | * @this {MediaCapabilities}
290 | * @param {!MediaDecodingConfiguration} requestedConfiguration The requested
291 | * decoding configuration.
292 | * @return {!Promise.} A Promise to a result
293 | * describing the capabilities of the browser in the request configuration.
294 | * @private
295 | */
296 | static async probeDecodingInfo_(requestedConfiguration) {
297 | console.assert(this == navigator.mediaCapabilities,
298 | 'bad "this" for decodingInfo');
299 |
300 | // Call the original version. If the call succeeds, we look at the result
301 | // to decide if the encryptionScheme field is supported or not.
302 | const capabilities =
303 | await McEncryptionSchemePolyfill.originalDecodingInfo_.call(
304 | this, requestedConfiguration);
305 |
306 | // If the config is not supported, we don't need to try anything else.
307 | if (!capabilities.supported) {
308 | return capabilities;
309 | }
310 |
311 | if (!requestedConfiguration.keySystemConfiguration) {
312 | // This was not a query regarding encrypted content. The results are
313 | // valid, but won't tell us anything about native support for
314 | // encryptionScheme. Just return the results.
315 | return capabilities;
316 | }
317 |
318 | const mediaKeySystemAccess = capabilities.keySystemAccess;
319 |
320 | if (mediaKeySystemAccess && hasEncryptionScheme(mediaKeySystemAccess)) {
321 | // The browser supports the encryptionScheme field!
322 | // No need for a patch. Revert back to the original implementation.
323 | console.debug('McEncryptionSchemePolyfill: ' +
324 | 'Native encryptionScheme support found.');
325 | // eslint-disable-next-line require-atomic-updates
326 | navigator.mediaCapabilities.decodingInfo =
327 | McEncryptionSchemePolyfill.originalDecodingInfo_;
328 | // Return the results, which are completely valid.
329 | return capabilities;
330 | }
331 |
332 | // If we land here, either the browser does not support the
333 | // encryptionScheme field, or the browser does not support EME-related
334 | // fields in MCap _at all_.
335 |
336 | // First, install a patch to check the mediaKeySystemAccess or
337 | // encryptionScheme field in future calls.
338 | console.debug('McEncryptionSchemePolyfill: ' +
339 | 'No native encryptionScheme support found. '+
340 | 'Patching encryptionScheme support.');
341 | // eslint-disable-next-line require-atomic-updates
342 | navigator.mediaCapabilities.decodingInfo =
343 | McEncryptionSchemePolyfill.polyfillDecodingInfo_;
344 |
345 | // Second, if _none_ of the EME-related fields of MCap are supported, fill
346 | // them in now before returning the results.
347 | if (!mediaKeySystemAccess) {
348 | capabilities.keySystemAccess =
349 | await McEncryptionSchemePolyfill.getMediaKeySystemAccess_(
350 | requestedConfiguration);
351 | return capabilities;
352 | }
353 |
354 | // If we land here, it's only the encryption scheme field that is missing.
355 | // The results we have may not be valid, since they didn't account for
356 | // encryption scheme. Run the query again through our polyfill.
357 | return McEncryptionSchemePolyfill.polyfillDecodingInfo_.call(
358 | this, requestedConfiguration);
359 | }
360 |
361 | /**
362 | * A polyfill for mediaCapabilities.decodingInfo to handle the
363 | * encryptionScheme field in browsers that don't support it. It uses the
364 | * user-agent string to guess what encryption schemes are supported, then
365 | * those guesses are used to reject unsupported schemes.
366 | *
367 | * @this {MediaCapabilities}
368 | * @param {!MediaDecodingConfiguration} requestedConfiguration The requested
369 | * decoding configuration.
370 | * @return {!Promise.} A Promise to a result
371 | * describing the capabilities of the browser in the request configuration.
372 | * @private
373 | */
374 | static async polyfillDecodingInfo_(requestedConfiguration) {
375 | console.assert(this == navigator.mediaCapabilities,
376 | 'bad "this" for decodingInfo');
377 |
378 | let videoScheme = null;
379 | let audioScheme = null;
380 |
381 | if (requestedConfiguration.keySystemConfiguration) {
382 | const keySystemConfig = requestedConfiguration.keySystemConfiguration;
383 |
384 | const keySystem = keySystemConfig.keySystem;
385 |
386 | audioScheme = keySystemConfig.audio &&
387 | keySystemConfig.audio.encryptionScheme;
388 | videoScheme = keySystemConfig.video &&
389 | keySystemConfig.video.encryptionScheme;
390 |
391 | const supportedScheme = guessSupportedScheme(keySystem);
392 |
393 | const notSupportedResult = {
394 | powerEfficient: false,
395 | smooth: false,
396 | supported: false,
397 | keySystemAccess: null,
398 | configuration: requestedConfiguration,
399 | };
400 |
401 | if (!checkSupportedScheme(audioScheme, supportedScheme)) {
402 | return notSupportedResult;
403 | }
404 | if (!checkSupportedScheme(videoScheme, supportedScheme)) {
405 | return notSupportedResult;
406 | }
407 | }
408 |
409 | // At this point, either it's unencrypted or we assume the encryption scheme
410 | // is supported. So delegate to the original decodingInfo() method.
411 | const capabilities =
412 | await McEncryptionSchemePolyfill.originalDecodingInfo_.call(
413 | this, requestedConfiguration);
414 |
415 | if (capabilities.keySystemAccess) {
416 | // If the result is supported and encrypted, this will be a
417 | // MediaKeySystemAccess instance. Wrap the MKSA object in ours to provide
418 | // the missing field in the returned configuration.
419 | capabilities.keySystemAccess =
420 | new EmeEncryptionSchemePolyfillMediaKeySystemAccess(
421 | capabilities.keySystemAccess, videoScheme, audioScheme);
422 | } else if (requestedConfiguration.keySystemConfiguration) {
423 | // If the result is supported and the content is encrypted, we should have
424 | // a MediaKeySystemAccess instance as part of the result. If we land
425 | // here, the browser doesn't support the EME-related fields of MCap.
426 | capabilities.keySystemAccess =
427 | await McEncryptionSchemePolyfill.getMediaKeySystemAccess_(
428 | requestedConfiguration);
429 | }
430 |
431 | return capabilities;
432 | }
433 |
434 | /**
435 | * Call navigator.requestMediaKeySystemAccess to get the MediaKeySystemAccess
436 | * information.
437 | *
438 | * @param {!MediaDecodingConfiguration} requestedConfiguration The requested
439 | * decoding configuration.
440 | * @return {!Promise.} A Promise to a
441 | * MediaKeySystemAccess instance.
442 | * @private
443 | */
444 | static async getMediaKeySystemAccess_(requestedConfiguration) {
445 | const mediaKeySystemConfig =
446 | McEncryptionSchemePolyfill.convertToMediaKeySystemConfig_(
447 | requestedConfiguration);
448 | const keySystemAccess =
449 | await navigator.requestMediaKeySystemAccess(
450 | requestedConfiguration.keySystemConfiguration.keySystem,
451 | [mediaKeySystemConfig]);
452 | return keySystemAccess;
453 | }
454 |
455 | /**
456 | * Convert the MediaDecodingConfiguration object to a
457 | * MediaKeySystemConfiguration object.
458 | *
459 | * @param {!MediaDecodingConfiguration} decodingConfig The decoding
460 | * configuration.
461 | * @return {!MediaKeySystemConfiguration} The converted MediaKeys
462 | * configuration.
463 | */
464 | static convertToMediaKeySystemConfig_(decodingConfig) {
465 | const mediaCapKeySystemConfig = decodingConfig.keySystemConfiguration;
466 | const audioCapabilities = [];
467 | const videoCapabilities = [];
468 |
469 | if (mediaCapKeySystemConfig.audio) {
470 | const capability = {
471 | robustness: mediaCapKeySystemConfig.audio.robustness || '',
472 | contentType: decodingConfig.audio.contentType,
473 | encryptionScheme: mediaCapKeySystemConfig.audio.encryptionScheme,
474 | };
475 | audioCapabilities.push(capability);
476 | }
477 |
478 | if (mediaCapKeySystemConfig.video) {
479 | const capability = {
480 | robustness: mediaCapKeySystemConfig.video.robustness || '',
481 | contentType: decodingConfig.video.contentType,
482 | encryptionScheme: mediaCapKeySystemConfig.video.encryptionScheme,
483 | };
484 | videoCapabilities.push(capability);
485 | }
486 |
487 | const initDataTypes = mediaCapKeySystemConfig.initDataType ?
488 | [mediaCapKeySystemConfig.initDataType] : [];
489 |
490 | /** @type {!MediaKeySystemConfiguration} */
491 | const mediaKeySystemConfig = {
492 | initDataTypes: initDataTypes,
493 | distinctiveIdentifier: mediaCapKeySystemConfig.distinctiveIdentifier,
494 | persistentState: mediaCapKeySystemConfig.persistentState,
495 | sessionTypes: mediaCapKeySystemConfig.sessionTypes,
496 | };
497 |
498 | // Only add the audio video capablities if they have valid data.
499 | // Otherwise the query will fail.
500 | if (audioCapabilities.length) {
501 | mediaKeySystemConfig.audioCapabilities = audioCapabilities;
502 | }
503 | if (videoCapabilities.length) {
504 | mediaKeySystemConfig.videoCapabilities = videoCapabilities;
505 | }
506 | return mediaKeySystemConfig;
507 | }
508 | }
509 |
510 | /**
511 | * A wrapper around MediaKeySystemAccess that adds encryptionScheme
512 | * fields to the configuration, to emulate what a browser with native support
513 | * for this field would do.
514 | *
515 | * @see https://github.com/w3c/encrypted-media/pull/457
516 | * @see https://github.com/WICG/encrypted-media-encryption-scheme/issues/13
517 | * @implements {MediaKeySystemAccess}
518 | */
519 | class EmeEncryptionSchemePolyfillMediaKeySystemAccess {
520 | /**
521 | * @param {!MediaKeySystemAccess} mksa A native MediaKeySystemAccess instance
522 | * to wrap.
523 | * @param {?string|undefined} videoScheme The encryption scheme to add to the
524 | * configuration for video.
525 | * @param {?string|undefined} audioScheme The encryption scheme to add to the
526 | * configuration for audio.
527 | */
528 | constructor(mksa, videoScheme, audioScheme) {
529 | /**
530 | * @const {!MediaKeySystemAccess}
531 | * @private
532 | */
533 | this.mksa_ = mksa;
534 |
535 | /**
536 | * @const {?string}
537 | * @private
538 | */
539 | this.videoScheme_ = videoScheme || null;
540 |
541 | /**
542 | * @const {?string}
543 | * @private
544 | */
545 | this.audioScheme_ = audioScheme || null;
546 |
547 | /** @const {string} */
548 | this.keySystem = mksa.keySystem;
549 | }
550 |
551 | /**
552 | * @override
553 | * @return {!MediaKeySystemConfiguration} A MediaKeys config with
554 | * encryptionScheme fields added
555 | */
556 | getConfiguration() {
557 | // A browser which supports the encryptionScheme field would always return
558 | // that field in the resulting configuration. So here, we emulate that.
559 | const configuration = this.mksa_.getConfiguration();
560 |
561 | if (configuration.videoCapabilities) {
562 | for (const capability of configuration.videoCapabilities) {
563 | capability['encryptionScheme'] = this.videoScheme_;
564 | }
565 | }
566 |
567 | if (configuration.audioCapabilities) {
568 | for (const capability of configuration.audioCapabilities) {
569 | capability['encryptionScheme'] = this.audioScheme_;
570 | }
571 | }
572 |
573 | return configuration;
574 | }
575 |
576 | /**
577 | * @override
578 | * @return {!Promise} A passthru of the native MediaKeys object
579 | */
580 | createMediaKeys() {
581 | return this.mksa_.createMediaKeys();
582 | }
583 | }
584 |
585 | /**
586 | * Guess the supported encryption scheme for the key system.
587 | *
588 | * @param {string} keySystem The key system ID.
589 | * @return {?string} A guess at the encryption scheme this key system
590 | * supports.
591 | */
592 | function guessSupportedScheme(keySystem) {
593 | if (keySystem.startsWith('com.widevine')) {
594 | return 'cenc';
595 | } else if (keySystem.startsWith('com.microsoft')) {
596 | return 'cenc';
597 | } else if (keySystem.startsWith('com.chromecast')) {
598 | return 'cenc';
599 | } else if (keySystem.startsWith('com.adobe')) {
600 | return 'cenc';
601 | } else if (keySystem.startsWith('org.w3')) {
602 | return 'cenc';
603 | } else if (keySystem.startsWith('com.apple')) {
604 | return 'cbcs';
605 | } else if (keySystem.startsWith('com.huawei')) {
606 | return 'cenc';
607 | }
608 |
609 | // We don't have this key system in our map!
610 |
611 | // Log a warning. The only way the request will succeed now is if the
612 | // app doesn't specify an encryption scheme in their own configs.
613 | // Use bracket notation to keep this from being stripped from the build.
614 | console['warn']('EmeEncryptionSchemePolyfill: Unknown key system:',
615 | keySystem, 'Please contribute!');
616 |
617 | return null;
618 | }
619 |
620 | /**
621 | * @param {?MediaKeySystemAccess} mediaKeySystemAccess A native
622 | * MediaKeySystemAccess instance from the browser.
623 | * @return {boolean} True if browser natively supports encryptionScheme.
624 | */
625 | function hasEncryptionScheme(mediaKeySystemAccess) {
626 | const configuration = mediaKeySystemAccess.getConfiguration();
627 |
628 | // It doesn't matter which capability we look at. For this check, they
629 | // should all produce the same result.
630 | const firstVideoCapability =
631 | configuration.videoCapabilities && configuration.videoCapabilities[0];
632 | const firstAudioCapability =
633 | configuration.audioCapabilities && configuration.audioCapabilities[0];
634 | const firstCapability = firstVideoCapability || firstAudioCapability;
635 |
636 | // If supported by the browser, the encryptionScheme field must appear in
637 | // the returned configuration, regardless of whether or not it was
638 | // specified in the supportedConfigurations given by the application.
639 | if (firstCapability && firstCapability['encryptionScheme'] !== undefined) {
640 | return true;
641 | }
642 | return false;
643 | }
644 |
645 | /**
646 | * @param {(string|undefined|null)} scheme Encryption scheme to check
647 | * @param {?string} supportedScheme A guess at the encryption scheme this
648 | * supports.
649 | * @return {boolean} True if the scheme is compatible.
650 | */
651 | function checkSupportedScheme(scheme, supportedScheme) {
652 | if (!scheme) {
653 | // Not encrypted = always supported
654 | return true;
655 | }
656 |
657 | if (scheme == supportedScheme) {
658 | // The assumed-supported legacy scheme for this platform.
659 | return true;
660 | }
661 |
662 | if (scheme == 'cbcs' || scheme == 'cbcs-1-9') {
663 | if (EncryptionSchemePolyfills.isRecentFirefox ||
664 | EncryptionSchemePolyfills.isRecentWebOS ||
665 | EncryptionSchemePolyfills.isChromecast) {
666 | // Firefox >= 100 supports CBCS, but doesn't support queries yet.
667 | // WebOS >= 6 supports CBCS, but doesn't support queries yet.
668 | // Older Chromecast devices are assumed to support CBCS as well.
669 | return true;
670 | }
671 | }
672 |
673 | return false;
674 | }
675 |
676 | /**
677 | * The original requestMediaKeySystemAccess, before we patched it.
678 | *
679 | * @type {
680 | * function(this:Navigator,
681 | * string,
682 | * !Array.
683 | * ):!Promise.
684 | * }
685 | * @private
686 | */
687 | EmeEncryptionSchemePolyfill.originalRMKSA_;
688 |
689 | /**
690 | * The original decodingInfo, before we patched it.
691 | *
692 | * @type {
693 | * function(this:MediaCapabilities,
694 | * !MediaDecodingConfiguration
695 | * ):!Promise.
696 | * }
697 | * @private
698 | */
699 | McEncryptionSchemePolyfill.originalDecodingInfo_;
700 |
701 | /**
702 | * A single entry point for both polyfills (EME & MC).
703 | *
704 | * @export
705 | */
706 | class EncryptionSchemePolyfills {
707 | /**
708 | * Installs both polyfills (EME & MC).
709 | *
710 | * @export
711 | */
712 | static install() {
713 | EmeEncryptionSchemePolyfill.install();
714 | McEncryptionSchemePolyfill.install();
715 | }
716 | }
717 |
718 | /**
719 | * @const {boolean}
720 | */
721 | EncryptionSchemePolyfills.isChromecast =
722 | navigator.userAgent.includes('CrKey');
723 |
724 | /**
725 | * @const {boolean}
726 | */
727 | EncryptionSchemePolyfills.isRecentFirefox =
728 | parseInt(navigator.userAgent.split('Firefox/').pop(), 10) >= 100;
729 |
730 | /**
731 | * @const {boolean}
732 | */
733 | EncryptionSchemePolyfills.isRecentWebOS = (() => {
734 | const userAgent = navigator.userAgent || '';
735 | const isWebOS = userAgent.includes('Web0S');
736 | if (!isWebOS) {
737 | return false;
738 | }
739 | const chromeVersionMatch = userAgent.match(/Chrome\/(\d+)/);
740 | if (!chromeVersionMatch) {
741 | return false;
742 | }
743 | const chromeVersion = parseInt(chromeVersionMatch[1], 10);
744 | return chromeVersion >= 79;
745 | })();
746 |
747 | // Support for CommonJS and AMD module formats.
748 | /** @suppress {undefinedVars} */
749 | (() => {
750 | if (typeof module !== 'undefined' && module.exports) {
751 | module.exports = EncryptionSchemePolyfills;
752 | }
753 | })();
754 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "eme-encryption-scheme-polyfill",
3 | "description": "A polyfill for the encryptionScheme field in EME",
4 | "version": "2.2.3",
5 | "license": "Apache-2.0",
6 | "author": "Google",
7 | "homepage": "https://github.com/shaka-project/eme-encryption-scheme-polyfill#readme",
8 | "maintainers": [
9 | {
10 | "name": "Joey Parrish",
11 | "email": "joeyparrish@google.com"
12 | }
13 | ],
14 | "bugs": {
15 | "url": "https://github.com/shaka-project/eme-encryption-scheme-polyfill/issues"
16 | },
17 | "scripts": {
18 | "test": "npm run lint && npm run closure-compiler-check && npm run build",
19 | "lint": "eslint index.js",
20 | "closure-compiler-check": "google-closure-compiler -O ADVANCED --generate_exports --js_output_file /dev/null --jscomp_error '*' closure-compiler-check/* index.js",
21 | "build": "browserify index.js -s EncryptionSchemePolyfills -t [ babelify --presets [ @babel/preset-env ] ] -t stripify -p tinyify -p browserify-header -o dist/eme-encryption-scheme-polyfill.js",
22 | "prepublishOnly": "npm test"
23 | },
24 | "devDependencies": {
25 | "@babel/core": "^7.17.2",
26 | "@babel/preset-env": "^7.16.11",
27 | "babel-plugin-transform-async-to-promises": "^0.8.18",
28 | "babelify": "^10.0.0",
29 | "browserify": "^17.0.0",
30 | "browserify-header": "^1.1.0",
31 | "eslint": "^8.8.0",
32 | "eslint-config-google": "^0.14.0",
33 | "eslint-plugin-jsdoc": "^37.8.2",
34 | "google-closure-compiler": "^20220202.0.0",
35 | "stripify": "^6.0.0",
36 | "tinyify": "^3.0.0"
37 | },
38 | "main": "index.js",
39 | "files": [
40 | "dist/eme-encryption-scheme-polyfill.js"
41 | ],
42 | "repository": {
43 | "type": "git",
44 | "url": "git+https://github.com/shaka-project/eme-encryption-scheme-polyfill.git"
45 | },
46 | "keywords": [
47 | "EME",
48 | "polyfill"
49 | ]
50 | }
51 |
--------------------------------------------------------------------------------