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 61
/
Copy pathProgram.cs
790 lines (686 loc) · 35.8 KB
/
Program.cs
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using Common_Utils;
using Microsoft.Azure.Management.Media;
using Microsoft.Azure.Management.Media.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.Linq;
using System.Security.Claims;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using WidevineConfig;
namespace EncryptWithDRM
{
class Program
{
private const string AdaptiveStreamingTransformName = "MyTransformWithAdaptiveStreamingPreset";
// Set this variable to true if you want to authenticate Interactively through the browser using your Azure user account
private const bool UseInteractiveAuth = false;
private const string SourceUri = "https://nimbuscdn-nimbuspm.streaming.mediaservices.windows.net/2b533311-b215-4409-80af-529c3e853622/Ignite-short.mp4";
private static readonly string Issuer = "myIssuer";
private static readonly string Audience = "myAudience";
private static byte[] TokenSigningKey = new byte[40];
private static readonly string ContentKeyPolicyName = "DRMContentKeyPolicy";
public static async Task Main(string[] args)
{
// If Visual Studio is used, let's read the .env file which should be in the root folder (same folder than the solution .sln file).
// Same code will work in VS Code, but VS Code uses also launch.json to get the .env file.
// You can create this ".env" file by saving the "sample.env" file as ".env" file and fill it with the right values.
try
{
DotEnv.Load(".env");
}
catch
{
}
ConfigWrapper config = new(new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables() // parses the values from the optional .env file at the solution root
.Build());
try
{
await RunAsync(config);
}
catch (Exception exception)
{
Console.Error.WriteLine($"{exception.Message}");
if (exception.GetBaseException() is ErrorResponseException apiException)
{
Console.Error.WriteLine(
$"ERROR: API call failed with error code '{apiException.Body.Error.Code}' and message '{apiException.Body.Error.Message}'.");
}
}
Console.WriteLine("Press Enter to continue.");
Console.ReadLine();
}
/// <summary>
/// Run the sample async.
/// </summary>
/// <param name="config">The parm is of type ConfigWrapper. This class reads values from local configuration file.</param>
/// <returns></returns>
// <RunAsync>
private static async Task RunAsync(ConfigWrapper config)
{
IAzureMediaServicesClient client;
try
{
client = await Authentication.CreateMediaServicesClientAsync(config, UseInteractiveAuth);
}
catch (Exception e)
{
Console.Error.WriteLine("TIP: Make sure that you have filled out the appsettings.json file before running this sample.");
Console.Error.WriteLine($"{e.Message}");
return;
}
// Set the polling interval for long running operations to 2 seconds.
// The default value is 30 seconds for the .NET client SDK
client.LongRunningOperationRetryTimeout = 2;
// Creating a unique suffix so that we don't have name collisions if you run the sample
// multiple times without cleaning up.
string uniqueness = Guid.NewGuid().ToString("N");
string jobName = $"job-{uniqueness}";
string locatorName = $"locator-{uniqueness}";
string outputAssetName = $"output-{uniqueness}";
// Ensure that you have the desired encoding Transform. This is really a one time setup operation.
Transform transform = await GetOrCreateTransformAsync(client, config.ResourceGroup, config.AccountName, AdaptiveStreamingTransformName);
// Output from the encoding Job must be written to an Asset, so let's create one
Asset outputAsset = await CreateOutputAssetAsync(client, config.ResourceGroup, config.AccountName, outputAssetName);
Job job = await SubmitJobAsync(client, config.ResourceGroup, config.AccountName, AdaptiveStreamingTransformName, outputAsset.Name, jobName);
// In this demo code, we will poll for Job status
// Polling is not a recommended best practice for production applications because of the latency it introduces.
// Overuse of this API may trigger throttling. Developers should instead use Event Grid.
job = await WaitForJobToFinishAsync(client, config.ResourceGroup, config.AccountName, AdaptiveStreamingTransformName, jobName);
if (job.State == JobState.Finished)
{
// Set a token signing key that you want to use
TokenSigningKey = Convert.FromBase64String(config.SymmetricKey);
// Create the content key policy that configures how the content key is delivered to end clients
// via the Key Delivery component of Azure Media Services.
// We are using the ContentKeyIdentifierClaim in the ContentKeyPolicy which means that the token presented
// to the Key Delivery Component must have the identifier of the content key in it.
ContentKeyPolicy policy = await GetOrCreateContentKeyPolicyAsync(client, config.ResourceGroup, config.AccountName, ContentKeyPolicyName, TokenSigningKey);
StreamingLocator locator = await CreateStreamingLocatorAsync(client, config.ResourceGroup, config.AccountName, outputAsset.Name, locatorName, ContentKeyPolicyName);
// In this example, we want to play the PlayReady (CENC) encrypted stream.
// We need to get the key identifier of the content key where its type is CommonEncryptionCenc.
string keyIdentifier = locator.ContentKeys.Where(k => k.Type == StreamingLocatorContentKeyType.CommonEncryptionCenc).First().Id.ToString();
Console.WriteLine($"KeyIdentifier = {keyIdentifier}");
// In order to generate our test token we must get the ContentKeyId to put in the ContentKeyIdentifierClaim claim.
string token = GetTokenAsync(Issuer, Audience, keyIdentifier, TokenSigningKey);
string dashPath = await GetDASHStreamingUrlAsync(client, config.ResourceGroup, config.AccountName, locator.Name);
Console.WriteLine("Copy and paste the following URL in your browser to play back the file in the Azure Media Player.");
Console.WriteLine("You can use Edge/IE11 for PlayReady and Chrome/Firefox for Widevine.");
Console.WriteLine();
Console.WriteLine($"https://ampdemo.azureedge.net/?url={dashPath}&playready=true&widevine=true&token=Bearer%3D{token}");
Console.WriteLine();
}
Console.WriteLine("When finished testing press enter to cleanup.");
Console.Out.Flush();
Console.ReadLine();
Console.WriteLine("Cleaning up...");
await CleanUpAsync(client, config.ResourceGroup, config.AccountName, AdaptiveStreamingTransformName, job.Name, new List<string> { outputAsset.Name }, ContentKeyPolicyName);
}
// </RunAsync>
/// <summary>
/// Create the content key policy that configures how the content key is delivered to end clients
/// via the Key Delivery component of Azure Media Services.
/// </summary>
/// <param name="client">The Media Services client.</param>
/// <param name="resourceGroupName">The name of the resource group within the Azure subscription.</param>
/// <param name="accountName"> The Media Services account name.</param>
/// <param name="contentKeyPolicyName">The name of the content key policy resource.</param>
/// <returns></returns>
// <GetOrCreateContentKeyPolicy>
private static async Task<ContentKeyPolicy> GetOrCreateContentKeyPolicyAsync(
IAzureMediaServicesClient client,
string resourceGroupName,
string accountName,
string contentKeyPolicyName,
byte[] tokenSigningKey)
{
bool createPolicy = false;
ContentKeyPolicy policy = null;
try
{
policy = await client.ContentKeyPolicies.GetAsync(resourceGroupName, accountName, contentKeyPolicyName);
}
catch (ErrorResponseException ex) when (ex.Response.StatusCode == System.Net.HttpStatusCode.NotFound)
{
createPolicy = true;
}
if (createPolicy)
{
ContentKeyPolicySymmetricTokenKey primaryKey = new ContentKeyPolicySymmetricTokenKey(tokenSigningKey);
List<ContentKeyPolicyTokenClaim> requiredClaims = new List<ContentKeyPolicyTokenClaim>()
{
ContentKeyPolicyTokenClaim.ContentKeyIdentifierClaim
};
List<ContentKeyPolicyRestrictionTokenKey> alternateKeys = null;
ContentKeyPolicyTokenRestriction restriction
= new ContentKeyPolicyTokenRestriction(Issuer, Audience, primaryKey, ContentKeyPolicyRestrictionTokenType.Jwt, alternateKeys, requiredClaims);
ContentKeyPolicyPlayReadyConfiguration playReadyConfig = ConfigurePlayReadyLicenseTemplate();
ContentKeyPolicyWidevineConfiguration widevineConfig = ConfigureWidevineLicenseTemplate();
// ContentKeyPolicyFairPlayConfiguration fairplayConfig = ConfigureFairPlayPolicyOptions();
List<ContentKeyPolicyOption> options = new List<ContentKeyPolicyOption>();
options.Add(
new ContentKeyPolicyOption()
{
Configuration = playReadyConfig,
// If you want to set an open restriction, use
// Restriction = new ContentKeyPolicyOpenRestriction()
Restriction = restriction
});
options.Add(
new ContentKeyPolicyOption()
{
Configuration = widevineConfig,
Restriction = restriction
});
// add CBCS ContentKeyPolicyOption into the list
// options.Add(
// new ContentKeyPolicyOption()
// {
// Configuration = fairplayConfig,
// Restriction = restriction,
// Name = "ContentKeyPolicyOption_CBCS"
// });
policy = await client.ContentKeyPolicies.CreateOrUpdateAsync(resourceGroupName, accountName, contentKeyPolicyName, options);
}
else
{
// Get the signing key from the existing policy.
var policyProperties = await client.ContentKeyPolicies.GetPolicyPropertiesWithSecretsAsync(resourceGroupName, accountName, contentKeyPolicyName);
if (policyProperties.Options[0].Restriction is ContentKeyPolicyTokenRestriction restriction)
{
if (restriction.PrimaryVerificationKey is ContentKeyPolicySymmetricTokenKey signingKey)
{
TokenSigningKey = signingKey.KeyValue;
}
}
}
return policy;
}
// </GetOrCreateContentKeyPolicy>
/// <summary>
/// If the specified transform exists, get that transform.
/// If the it does not exist, creates a new transform with the specified output.
/// In this case, the output is set to encode a video using one of the built-in encoding presets.
/// </summary>
/// <param name="client">The Media Services client.</param>
/// <param name="resourceGroupName">The name of the resource group within the Azure subscription.</param>
/// <param name="accountName"> The Media Services account name.</param>
/// <param name="transformName">The name of the transform.</param>
/// <returns></returns>
// <EnsureTransformExists>
private static async Task<Transform> GetOrCreateTransformAsync(
IAzureMediaServicesClient client,
string resourceGroupName,
string accountName,
string transformName)
{
bool createTransform = false;
Transform transform = null;
try
{
// Does a transform already exist with the desired name? Assume that an existing Transform with the desired name
// also uses the same recipe or Preset for processing content.
transform = client.Transforms.Get(resourceGroupName, accountName, transformName);
}
catch (ErrorResponseException ex) when (ex.Response.StatusCode == System.Net.HttpStatusCode.NotFound)
{
createTransform = true;
}
if (createTransform)
{
// You need to specify what you want it to produce as an output
TransformOutput[] output = new TransformOutput[]
{
new TransformOutput
{
// The preset for the Transform is set to one of Media Services built-in sample presets.
// You can customize the encoding settings by changing this to use "StandardEncoderPreset" class.
Preset = new BuiltInStandardEncoderPreset()
{
// This sample uses the built-in encoding preset for Adaptive Bitrate Streaming.
PresetName = EncoderNamedPreset.AdaptiveStreaming
}
}
};
// Create the Transform with the output defined above
transform = await client.Transforms.CreateOrUpdateAsync(resourceGroupName, accountName, transformName, output);
}
return transform;
}
// </EnsureTransformExists>
/// <summary>
/// Creates an ouput asset. The output from the encoding Job must be written to an Asset.
/// </summary>
/// <param name="client">The Media Services client.</param>
/// <param name="resourceGroupName">The name of the resource group within the Azure subscription.</param>
/// <param name="accountName"> The Media Services account name.</param>
/// <param name="assetName">The output asset name.</param>
/// <returns></returns>
// <CreateOutputAsset>
private static async Task<Asset> CreateOutputAssetAsync(IAzureMediaServicesClient client, string resourceGroupName, string accountName, string assetName)
{
bool existingAsset = true;
Asset outputAsset;
try
{
// Check if an Asset already exists
outputAsset = await client.Assets.GetAsync(resourceGroupName, accountName, assetName);
}
catch (ErrorResponseException ex) when (ex.Response.StatusCode == System.Net.HttpStatusCode.NotFound)
{
existingAsset = false;
}
Asset asset = new Asset();
string outputAssetName = assetName;
if (existingAsset)
{
// Name collision! In order to get the sample to work, let's just go ahead and create a unique asset name
// Note that the returned Asset can have a different name than the one specified as an input parameter.
// You may want to update this part to throw an Exception instead, and handle name collisions differently.
string uniqueness = $"-{Guid.NewGuid():N}";
outputAssetName += uniqueness;
Console.WriteLine("Warning – found an existing Asset with name = " + assetName);
Console.WriteLine("Creating an Asset with this name instead: " + outputAssetName);
}
return await client.Assets.CreateOrUpdateAsync(resourceGroupName, accountName, outputAssetName, asset);
}
// </CreateOutputAsset>
/// <summary>
/// Submits a request to Media Services to apply the specified Transform to a given input video.
/// </summary>
/// <param name="client">The Media Services client.</param>
/// <param name="resourceGroupName">The name of the resource group within the Azure subscription.</param>
/// <param name="accountName"> The Media Services account name.</param>
/// <param name="transformName">The name of the transform.</param>
/// <param name="outputAssetName">The (unique) name of the output asset that will store the result of the encoding job. </param>
/// <param name="jobName">The (unique) name of the job.</param>
/// <returns></returns>
// <SubmitJob>
private static async Task<Job> SubmitJobAsync(IAzureMediaServicesClient client,
string resourceGroup,
string accountName,
string transformName,
string outputAssetName,
string jobName)
{
// This example shows how to encode from any HTTPs source URL - a new feature of the v3 API.
// Change the URL to any accessible HTTPs URL or SAS URL from Azure.
JobInputHttp jobInput =
new JobInputHttp(files: new[] { SourceUri });
JobOutput[] jobOutputs =
{
new JobOutputAsset(outputAssetName),
};
// In this example, we are assuming that the job name is unique.
//
// If you already have a job with the desired name, use the Jobs.Get method
// to get the existing job. In Media Services v3, the Get method on entities returns null
// if the entity doesn't exist (a case-insensitive check on the name).
Job job = await client.Jobs.CreateAsync(
resourceGroup,
accountName,
transformName,
jobName,
new Job
{
Input = jobInput,
Outputs = jobOutputs,
});
return job;
}
// </SubmitJob>
/// <summary>
/// Polls Media Services for the status of the Job.
/// </summary>
/// <param name="client">The Media Services client.</param>
/// <param name="resourceGroupName">The name of the resource group within the Azure subscription.</param>
/// <param name="accountName"> The Media Services account name.</param>
/// <param name="transformName">The name of the transform.</param>
/// <param name="jobName">The name of the job you submitted.</param>
/// <returns></returns>
// <WaitForJobToFinish>
private static async Task<Job> WaitForJobToFinishAsync(IAzureMediaServicesClient client,
string resourceGroupName,
string accountName,
string transformName,
string jobName)
{
const int SleepIntervalMs = 20 * 1000;
Job job;
do
{
job = await client.Jobs.GetAsync(resourceGroupName, accountName, transformName, jobName);
Console.WriteLine($"Job is '{job.State}'.");
for (int i = 0; i < job.Outputs.Count; i++)
{
JobOutput output = job.Outputs[i];
Console.Write($"\tJobOutput[{i}] is '{output.State}'.");
if (output.State == JobState.Processing)
{
Console.Write($" Progress (%): '{output.Progress}'.");
}
Console.WriteLine();
}
if (job.State != JobState.Finished && job.State != JobState.Error && job.State != JobState.Canceled)
{
await Task.Delay(SleepIntervalMs);
}
}
while (job.State != JobState.Finished && job.State != JobState.Error && job.State != JobState.Canceled);
return job;
}
// </WaitForJobToFinish>
/// <summary>
/// Configures PlayReady license template.
/// </summary>
/// <returns></returns>
//<ConfigurePlayReadyLicenseTemplate>
private static ContentKeyPolicyPlayReadyConfiguration ConfigurePlayReadyLicenseTemplate()
{
ContentKeyPolicyPlayReadyLicense objContentKeyPolicyPlayReadyLicense;
objContentKeyPolicyPlayReadyLicense = new ContentKeyPolicyPlayReadyLicense
{
AllowTestDevices = true,
BeginDate = new DateTime(2016, 1, 1),
ContentKeyLocation = new ContentKeyPolicyPlayReadyContentEncryptionKeyFromHeader(),
ContentType = ContentKeyPolicyPlayReadyContentType.UltraVioletStreaming,
LicenseType = ContentKeyPolicyPlayReadyLicenseType.Persistent,
PlayRight = new ContentKeyPolicyPlayReadyPlayRight
{
ImageConstraintForAnalogComponentVideoRestriction = true,
ExplicitAnalogTelevisionOutputRestriction = new ContentKeyPolicyPlayReadyExplicitAnalogTelevisionRestriction(true, 2),
AllowPassingVideoContentToUnknownOutput = ContentKeyPolicyPlayReadyUnknownOutputPassingOption.Allowed
}
};
ContentKeyPolicyPlayReadyConfiguration objContentKeyPolicyPlayReadyConfiguration = new ContentKeyPolicyPlayReadyConfiguration
{
Licenses = new List<ContentKeyPolicyPlayReadyLicense> { objContentKeyPolicyPlayReadyLicense }
};
return objContentKeyPolicyPlayReadyConfiguration;
}
// </ConfigurePlayReadyLicenseTemplate>
/// <summary>
/// Configures Widevine license template.
/// </summary>
/// <returns></returns>
// <ConfigureWidevineLicenseTemplate>
private static ContentKeyPolicyWidevineConfiguration ConfigureWidevineLicenseTemplate()
{
WidevineTemplate template = new WidevineTemplate()
{
AllowedTrackTypes = "SD_HD",
ContentKeySpecs = new ContentKeySpec[]
{
new ContentKeySpec()
{
TrackType = "SD",
SecurityLevel = 1,
RequiredOutputProtection = new OutputProtection()
{
HDCP = "HDCP_NONE"
}
}
},
PolicyOverrides = new PolicyOverrides()
{
CanPlay = true,
CanPersist = true,
CanRenew = false,
RentalDurationSeconds = 2592000,
PlaybackDurationSeconds = 10800,
LicenseDurationSeconds = 604800,
}
};
ContentKeyPolicyWidevineConfiguration objContentKeyPolicyWidevineConfiguration = new ContentKeyPolicyWidevineConfiguration
{
WidevineTemplate = Newtonsoft.Json.JsonConvert.SerializeObject(template)
};
return objContentKeyPolicyWidevineConfiguration;
}
// </ConfigureWidevineLicenseTemplate>
/// <summary>
/// Configures FairPlay policy options.
/// </summary>
/// <returns></returns>
// <ConfigureFairPlayPolicyOptions>
private static ContentKeyPolicyFairPlayConfiguration ConfigureFairPlayPolicyOptions()
{
string askHex = "";
string FairPlayPfxPassword = "";
var appCert = new X509Certificate2("FairPlayPfxPath", FairPlayPfxPassword, X509KeyStorageFlags.Exportable);
byte[] askBytes = Enumerable
.Range(0, askHex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(askHex.Substring(x, 2), 16))
.ToArray();
ContentKeyPolicyFairPlayConfiguration fairPlayConfiguration =
new ContentKeyPolicyFairPlayConfiguration
{
Ask = askBytes,
FairPlayPfx =
Convert.ToBase64String(appCert.Export(X509ContentType.Pfx, FairPlayPfxPassword)),
FairPlayPfxPassword = FairPlayPfxPassword,
RentalAndLeaseKeyType =
ContentKeyPolicyFairPlayRentalAndLeaseKeyType
.PersistentUnlimited,
RentalDuration = 2249
};
return fairPlayConfiguration;
}
// </ConfigureFairPlayPolicyOptions>
/// <summary>
/// Creates a StreamingLocator for the specified asset and with the specified streaming policy name.
/// Once the StreamingLocator is created the output asset is available to clients for playback.
///
/// This StreamingLocator uses "Predefined_MultiDrmCencStreaming"
/// because this sample encrypts with PlayReady and Widevine (CENC encryption).
///
/// </summary>
/// <param name="client">The Media Services client.</param>
/// <param name="resourceGroupName">The name of the resource group within the Azure subscription.</param>
/// <param name="accountName"> The Media Services account name.</param>
/// <param name="assetName">The name of the output asset.</param>
/// <param name="locatorName">The StreamingLocator name (unique in this case).</param>
/// <returns></returns>
// <CreateStreamingLocator>
private static async Task<StreamingLocator> CreateStreamingLocatorAsync(
IAzureMediaServicesClient client,
string resourceGroup,
string accountName,
string assetName,
string locatorName,
string contentPolicyName)
{
// If you also added FairPlay, use "Predefined_MultiDrmStreaming
StreamingLocator locator = await client.StreamingLocators.CreateAsync(
resourceGroup,
accountName,
locatorName,
new StreamingLocator
{
AssetName = assetName,
// "Predefined_MultiDrmCencStreaming" policy supports envelope and cenc encryption
// And sets two content keys on the StreamingLocator
StreamingPolicyName = "Predefined_MultiDrmCencStreaming",
DefaultContentKeyPolicyName = contentPolicyName
});
return locator;
}
// </CreateStreamingLocator>
/// <summary>
/// Create a token that will be used to protect your stream.
/// Only authorized clients would be able to play the video.
/// </summary>
/// <param name="issuer">The issuer is the secure token service that issues the token. </param>
/// <param name="audience">The audience, sometimes called scope, describes the intent of the token or the resource the token authorizes access to. </param>
/// <param name="keyIdentifier">The content key ID.</param>
/// <param name="tokenVerificationKey">Contains the key that the token was signed with. </param>
/// <returns></returns>
// <GetToken>
private static string GetTokenAsync(string issuer, string audience, string keyIdentifier, byte[] tokenVerificationKey)
{
var tokenSigningKey = new SymmetricSecurityKey(tokenVerificationKey);
SigningCredentials cred = new SigningCredentials(
tokenSigningKey,
// Use the HmacSha256 and not the HmacSha256Signature option, or the token will not work!
SecurityAlgorithms.HmacSha256,
SecurityAlgorithms.Sha256Digest);
Claim[] claims = new Claim[]
{
new Claim(ContentKeyPolicyTokenClaim.ContentKeyIdentifierClaim.ClaimType, keyIdentifier)
};
// To set a limit on how many times the same token can be used to request a key or a license.
// add the "urn:microsoft:azure:mediaservices:maxuses" claim.
// For example, claims.Add(new Claim("urn:microsoft:azure:mediaservices:maxuses", 4));
JwtSecurityToken token = new JwtSecurityToken(
issuer: issuer,
audience: audience,
claims: claims,
notBefore: DateTime.Now.AddMinutes(-5),
expires: DateTime.Now.AddMinutes(60),
signingCredentials: cred);
JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
return handler.WriteToken(token);
}
// </GetToken>
/// <summary>
/// Checks if the "default" streaming endpoint is in the running state,
/// if not, starts it.
/// Then, builds the streaming URLs.
/// </summary>
/// <param name="client">The Media Services client.</param>
/// <param name="resourceGroupName">The name of the resource group within the Azure subscription.</param>
/// <param name="accountName"> The Media Services account name.</param>
/// <param name="locatorName">The name of the StreamingLocator that was created.</param>
/// <returns></returns>
// <GetMPEGStreamingUrl>
private static async Task<string> GetDASHStreamingUrlAsync(
IAzureMediaServicesClient client,
string resourceGroupName,
string accountName,
string locatorName)
{
const string DefaultStreamingEndpointName = "default";
string dashPath = "";
StreamingEndpoint streamingEndpoint = await client.StreamingEndpoints.GetAsync(resourceGroupName, accountName, DefaultStreamingEndpointName);
if (streamingEndpoint.ResourceState != StreamingEndpointResourceState.Running)
{
await client.StreamingEndpoints.StartAsync(resourceGroupName, accountName, DefaultStreamingEndpointName);
}
ListPathsResponse paths = await client.StreamingLocators.ListPathsAsync(resourceGroupName, accountName, locatorName);
foreach (StreamingPath path in paths.StreamingPaths)
{
UriBuilder uriBuilder = new UriBuilder
{
Scheme = "https",
Host = streamingEndpoint.HostName
};
// Look for just the DASH path and generate a URL for the Azure Media Player to playback the content with the AES token to decrypt.
// Note that the JWT token is set to expire in 1 hour.
if (path.StreamingProtocol == StreamingPolicyStreamingProtocol.Dash)
{
uriBuilder.Path = path.Paths[0];
dashPath = uriBuilder.ToString();
}
}
return dashPath;
}
// </GetMPEGStreamingUrl>
/// <summary>
/// Downloads the results from the specified output asset, so you can see what you got.
/// </summary>
/// <param name="client">The Media Services client.</param>
/// <param name="resourceGroupName">The name of the resource group within the Azure subscription.</param>
/// <param name="accountName"> The Media Services account name.</param>
/// <param name="assetName">The output asset.</param>
/// <param name="outputFolderName">The name of the folder into which to download the results.</param>
// <DownloadResults>
private static async Task DownloadOutputAssetAsync(
IAzureMediaServicesClient client,
string resourceGroup,
string accountName,
string assetName,
string outputFolderName)
{
if (!Directory.Exists(outputFolderName))
{
Directory.CreateDirectory(outputFolderName);
}
AssetContainerSas assetContainerSas = await client.Assets.ListContainerSasAsync(
resourceGroup,
accountName,
assetName,
permissions: AssetContainerPermission.Read,
expiryTime: DateTime.UtcNow.AddHours(1).ToUniversalTime());
Uri containerSasUrl = new Uri(assetContainerSas.AssetContainerSasUrls.FirstOrDefault());
BlobContainerClient container = new BlobContainerClient(containerSasUrl);
string directory = Path.Combine(outputFolderName, assetName);
Directory.CreateDirectory(directory);
Console.WriteLine($"Downloading output results to '{directory}'...");
string continuationToken = null;
IList<Task> downloadTasks = new List<Task>();
do
{
var resultSegment = container.GetBlobs().AsPages(continuationToken);
foreach (Azure.Page<BlobItem> blobPage in resultSegment)
{
foreach (BlobItem blobItem in blobPage.Values)
{
var blobClient = container.GetBlobClient(blobItem.Name);
string filename = Path.Combine(directory, blobItem.Name);
downloadTasks.Add(blobClient.DownloadToAsync(filename));
}
// Get the continuation token and loop until it is empty.
continuationToken = blobPage.ContinuationToken;
}
} while (continuationToken != "");
await Task.WhenAll(downloadTasks);
Console.WriteLine("Download complete.");
}
// </DownloadResults>
/// <summary>
/// Deletes the jobs, assets and potentially the content key policy that were created.
/// Generally, you should clean up everything except objects
/// that you are planning to reuse (typically, you will reuse Transforms, and you will persist output assets and StreamingLocators).
/// </summary>
/// <param name="client"></param>
/// <param name="resourceGroupName"></param>
/// <param name="accountName"></param>
/// <param name="transformName"></param>
/// <param name="jobName"></param>
/// <param name="assetNames"></param>
/// <param name="contentKeyPolicyName"></param>
/// <returns></returns>
// <CleanUp>
private static async Task CleanUpAsync(
IAzureMediaServicesClient client,
string resourceGroupName,
string accountName,
string transformName,
string jobName,
List<string> assetNames,
string contentKeyPolicyName = null
)
{
await client.Jobs.DeleteAsync(resourceGroupName, accountName, transformName, jobName);
foreach (var assetName in assetNames)
{
await client.Assets.DeleteAsync(resourceGroupName, accountName, assetName);
}
if (contentKeyPolicyName != null)
{
client.ContentKeyPolicies.Delete(resourceGroupName, accountName, contentKeyPolicyName);
}
}
// </CleanUp>
}
}