This repository was archived by the owner on Apr 1, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathindex.ts
325 lines (260 loc) · 11.4 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { DefaultAzureCredential } from "@azure/identity";
import {
AzureMediaServices,
Transform,
KnownEncoderNamedPreset,
Asset,
KnownAssetContainerPermission,
KnownJobState,
StreamingEndpoint,
StreamingLocator,
KnownStreamingEndpointResourceState,
ContentKeyPolicyClearKeyConfiguration,
ContentKeyPolicyTokenRestriction,
ContentKeyPolicySymmetricTokenKey,
ContentKeyPolicy,
KnownContentKeyPolicyRestrictionTokenType,
} from '@azure/arm-mediaservices';
import {
BlobServiceClient,
AnonymousCredential
} from "@azure/storage-blob";
import * as crypto from "crypto";
import * as jwt from "jsonwebtoken";
// Load the .env file if it exists
import * as dotenv from "dotenv";
import * as path from "path";
dotenv.config();
// This is the main Media Services client object
let mediaServicesClient: AzureMediaServices;
const subscriptionId: string = process.env.AZURE_SUBSCRIPTION_ID as string; // this should be in the format 00000000-0000-0000-0000-000000000000
const resourceGroup: string = process.env.AZURE_RESOURCE_GROUP as string;
const accountName: string = process.env.AZURE_MEDIA_SERVICES_ACCOUNT_NAME as string;
// This sample uses the default Azure Credential object, which relies on the environment variable settings.
// If you wish to use User assigned managed identity, see the samples for v2 of @azure/identity
// Managed identity authentication is supported via either the DefaultAzureCredential or the ManagedIdentityCredential classes
// https://docs.microsoft.com/javascript/api/overview/azure/identity-readme?view=azure-node-latest
// See the following examples for how to authenticate in Azure with managed identity
// https://github.com/Azure/azure-sdk-for-js/blob/@azure/identity_2.0.1/sdk/identity/identity/samples/AzureIdentityExamples.md#authenticating-in-azure-with-managed-identity
// If you have issues with using the Visual Studio Azure identity, see https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/identity/identity/TROUBLESHOOTING.md#troubleshoot-default-azure-credential-authentication-issues
const credential = new DefaultAzureCredential();
// "Media\\<<yourfilepath.mp4>>"; // Place your media in the /Media folder at the root of the samples. Code for upload uses relative path to current working directory for Node;
let inputFile: string = "Media\\ignite.mp4";
///////////////////////////////////////////
// Main entry point for sample script //
///////////////////////////////////////////
export async function main() {
let runIndex = new Date().getTime().toString();
mediaServicesClient = new AzureMediaServices(credential, subscriptionId, {});
let mediaServiceAccount = await mediaServicesClient.mediaservices.get(resourceGroup, accountName);
console.log(`Using media service account ID : ${mediaServiceAccount.mediaServiceId}`);
let transform = await CreateTransformAsync(mediaServicesClient);
if (transform && transform.name) {
let outputAsset = await EncodeFileAsync(mediaServicesClient, transform.name, inputFile, runIndex);
let streamingEndpoint = await StartStreamingEndpointAsync(mediaServicesClient);
let password = "mango apple bananas"; // update this to any value you like
let contentKeyPolicy = await CreateContentKeyPolicyAsync(mediaServicesClient, password, runIndex);
let streamingLocator = await CreateStreamingLocatorAsync(mediaServicesClient, outputAsset, contentKeyPolicy, runIndex);
console.log();
let streamingUri = `https://${streamingEndpoint.hostName}/${streamingLocator.streamingLocatorId}/${path.basename(inputFile).split('.')[0]}.ism/manifest`;
console.log(`Steaming URL: ${streamingUri}`);
console.log();
let playbackToken = CreateToken(password);
console.log(`Watch your video at: https://aka.ms/azuremediaplayer?url=${encodeURI(streamingUri)}&aes=true&aestoken=${playbackToken}`);
console.log(`Playback token: ${playbackToken}`);
}
}
async function CreateTransformAsync(mediaServices: AzureMediaServices): Promise<Transform> {
console.log("Creating transform");
var transformName = "content-aware-transform";
try {
let transform = await mediaServices.transforms.get(resourceGroup, accountName, transformName);
return transform;
} catch (err) {
console.log(`Transform ${transformName} does not exist.`);
// Create a new Transform using a preset name from the list of built in encoding presets.
// To use a custom encoding preset, you can change this to be a StandardEncoderPreset, which has support for codecs, formats, and filter definitions.
// This sample uses the 'ContentAwareEncoding' preset which chooses the best output based on an analysis of the input video.
let transform = await mediaServices.transforms.createOrUpdate(resourceGroup, accountName, transformName,
{
name: transformName,
outputs: [{
preset: {
odataType: "#Microsoft.Media.BuiltInStandardEncoderPreset",
presetName: KnownEncoderNamedPreset.ContentAwareEncoding,
}
}]
});
return transform;
}
}
// Helper function to add an hour to the current time for use with the blob client uploader
function addHours(numOfHours: number, date = new Date()): Date {
date.setTime(date.getTime() + numOfHours * 60 * 60 * 1000);
return date;
}
async function EncodeFileAsync(
mediaServices: AzureMediaServices,
transformName: string,
inputFilePath: string,
runIndex: string): Promise<Asset> {
console.log("Creating input asset");
let inputAssetName = `input-asset-${runIndex}`;
let inputAsset = await mediaServices.assets.createOrUpdate(
resourceGroup,
accountName,
inputAssetName,
{}
);
let listContainerSas = await mediaServices.assets.listContainerSas(resourceGroup,
accountName,
inputAssetName,
{
expiryTime: addHours(1),
permissions: KnownAssetContainerPermission.ReadWriteDelete
})
if (listContainerSas.assetContainerSasUrls) {
console.log("Uploading input asset media");
let uploadSasUrl = listContainerSas.assetContainerSasUrls[0];
let fileName = path.basename(inputFilePath);
let inputAssetContainer = new BlobServiceClient(uploadSasUrl, new AnonymousCredential()).getContainerClient('');
let inputAssetBlob = inputAssetContainer.getBlockBlobClient(fileName);
await inputAssetBlob.uploadFile(inputFilePath,
{
blockSize: 4 * 1024 * 1024, // 4MB Block size
concurrency: 20, // 20 concurrent
onProgress: (ev) => console.log(ev)
}
);
}
console.log("Creating output asset");
let outputAssetName = `output-asset-${runIndex}`;
let outputAsset = await mediaServices.assets.createOrUpdate(
resourceGroup,
accountName,
outputAssetName,
{});
console.log("Starting encoding job");
let jobName = `job-${runIndex}`;
var job = await mediaServices.jobs.create(
resourceGroup,
accountName,
transformName,
jobName,
{
input: {
odataType: "#Microsoft.Media.JobInputAsset",
assetName: inputAssetName
},
outputs: [{
odataType: "#Microsoft.Media.JobOutputAsset",
assetName: outputAssetName,
}]
}
);
while (
job.state == KnownJobState.Processing ||
job.state == KnownJobState.Queued ||
job.state == KnownJobState.Scheduled) {
if (job.outputs) {
console.log(`Waiting for job to complete... ${job.state}, ${job.outputs[0].progress}% complete`);
}
await sleep(10000);
job = await mediaServicesClient.jobs.get(resourceGroup, accountName, transformName, jobName);
}
console.log(`Final job state ${job.state}`);
return outputAsset;
}
function sleep(ms: number) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
async function StartStreamingEndpointAsync(
mediaServices: AzureMediaServices): Promise<StreamingEndpoint> {
let defaultStreamingEndpoint: StreamingEndpoint =
await mediaServices.streamingEndpoints.get(resourceGroup, accountName, "default");
if (defaultStreamingEndpoint.resourceState != KnownStreamingEndpointResourceState.Running) {
console.log("Starting default streaming endpoint");
await mediaServicesClient.streamingEndpoints.beginStartAndWait(resourceGroup, accountName, "default", { updateIntervalInMs: 10000 })
}
return defaultStreamingEndpoint;
}
async function CreateStreamingLocatorAsync(
mediaServices: AzureMediaServices,
outputAsset: Asset,
contentKeyPolicy: ContentKeyPolicy,
runIndex: string): Promise<StreamingLocator> {
console.log("Creating streaming locator");
return await mediaServices.streamingLocators.create(
resourceGroup,
accountName,
`locator-${runIndex}`,
{
assetName: outputAsset.name,
streamingPolicyName: "Predefined_ClearKey",
defaultContentKeyPolicyName: contentKeyPolicy.name
});
}
async function CreateContentKeyPolicyAsync(
mediaServices: AzureMediaServices,
password: string,
runIndex: string): Promise<ContentKeyPolicy> {
console.log("Creating content key policy");
let configuration: ContentKeyPolicyClearKeyConfiguration = {
odataType: "#Microsoft.Media.ContentKeyPolicyClearKeyConfiguration",
}
let primaryKey: ContentKeyPolicySymmetricTokenKey = {
odataType: "#Microsoft.Media.ContentKeyPolicySymmetricTokenKey",
keyValue: DeriveKey(password),
}
let restriction: ContentKeyPolicyTokenRestriction = {
odataType: "#Microsoft.Media.ContentKeyPolicyTokenRestriction",
issuer: "urn:microsoft:azure:mediaservices",
audience: "urn:microsoft:azure:mediaservices",
primaryVerificationKey: primaryKey,
restrictionTokenType: KnownContentKeyPolicyRestrictionTokenType.Jwt
}
return (await mediaServices.contentKeyPolicies.createOrUpdate(
resourceGroup,
accountName,
`ckp-${runIndex}`,
{
options: [
{
configuration: configuration,
restriction: restriction,
name: "option1"
}
]
}));
}
function DeriveKey(password: string) {
let hash = crypto.createHash('sha256');
hash.update(new TextEncoder().encode(password));
return hash.digest().subarray(0, 16)
}
function CreateToken(password: string): string {
var tokenKey = DeriveKey(password)
let jwtToken = jwt.sign(
{},
Buffer.from(tokenKey),
{
algorithm: "HS256",
issuer: "urn:microsoft:azure:mediaservices",
audience: "urn:microsoft:azure:mediaservices",
expiresIn: "4h",
}
);
return jwtToken;
}
main().catch((err) => {
console.error("Error running sample:", err.message);
console.error(`Error code: ${err.code}`);
if (err.name == 'RestError') {
// REST API Error message
console.error("Error request:\n\n", err.request);
}
});