-
Notifications
You must be signed in to change notification settings - Fork 2
/
AdvancedEncodingAndPublishing.cs
726 lines (641 loc) · 34.3 KB
/
AdvancedEncodingAndPublishing.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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Azure.Identity;
using Azure.Storage.Blobs;
using Microsoft.Extensions.Configuration;
using MK.IO;
using MK.IO.Models;
namespace Sample
{
/// <summary>
/// Sample code for MK.IO using MK.IO .NET SDK that does the following:
/// - upload a mp4 file to a new asset using authentication in the browser (you need contribution role on the storage)
/// - create the output encoded asset
/// - create/update a encoding transform
/// - submit an encoding job
/// - create/update a transform to do the transcription of the video
/// - submit a job to generate the transcription (vtt)
/// - create/update a transform to insert the vtt as a text track
/// - submit a job to insert the vtt as a text track in the encoded asset
/// - create/update a transform for thumbnails
/// - submit a job to generate a thumbnails sprite
/// - create a download locator for the thumbnails sprite and thumbnails vtt and list the Urls
/// - create a streaming locator for the encoded asset
/// - create and start a streaming endpoint if there is none
/// - list the streaming urls and test player urls.
/// - clean the created resources if the user accepts
/// </summary>
public class AdvancedEncodingAndPublishing
{
private const string _encodingTransformName = "H264MultipleBitrate720pTransform";
private const EncoderNamedPreset _encodingPreset = EncoderNamedPreset.H264MultipleBitrate720p;
private const string _thumbnailTransformName = "ThumbnailTransform";
private const string _vodTranscriptionTransformName = "VODTranscriptionTransform";
private const string _textTrackInsertionTransformName = "TextTrackInserterTransform";
private const string _inputMP4FileName = @"Ignite.mp4";
private const string _bitmovinPlayer = "https://bitmovin.com/demos/stream-test?format={0}&manifest={1}";
public static async Task RunAsync()
{
/* you need to add an appsettings.json file with the following content:
{
"MKIOSubscriptionName": "yourMKIOsubscriptionname",
"MKIOToken": "yourMKIOPersonalAPIToken",
"StorageName": "yourStorageAccountName",
"TenantId" : "your Azure tenant ID " // optional
}
*/
Console.WriteLine("Sample for MK.IO that uploads a file in a new asset, does a video encoding to multiple bitrate, generates and inserts a VTT as text track, generates a thumbnails sprite and publishes the output asset for clear streaming.");
Console.WriteLine();
// Load settings from the appsettings.json file and check them
IConfigurationRoot config = LoadAndCheckSettings();
// Creating a unique suffix so that we don't have name collisions if you run the sample
// multiple times without cleaning up.
string uniqueId = MKIOClient.GenerateUniqueName(string.Empty);
string inputAssetName = $"input-{uniqueId}";
string outputEncodedAssetName = $"output-{uniqueId}-encoded";
string encodingJobName = $"job-{uniqueId}-encoding";
string locatorName = $"locator-{uniqueId}";
string outputThumbnailAssetName = $"{outputEncodedAssetName}-thumbnail";
string thumbnailJobName = $"job-{uniqueId}-thumbnail";
string locatorThumbnailName = $"{locatorName}-thumbnail";
string outputVTTAssetName = $"{inputAssetName}-transcription";
string vodTranscriptionJobName = $"job-{uniqueId}-vodtranscription";
string textTrackInsertionJobName = $"job-{uniqueId}-texttrackinsertion";
// MK.IO Client creation
var client = new MKIOClient(config["MKIOSubscriptionName"]!, config["MKIOToken"]!);
// Main video encoding ------------------------------------------------------------------------------------------------------------------------------------------
// Create a new input Asset and upload the specified local video file into it. We use the delete flag to delete the blob and container if we delete the asset in MK.IO
_ = await CreateInputAssetAndUploadFileAsync(client, config["StorageName"]!, config["TenantId"]!, inputAssetName, _inputMP4FileName);
// Output from the encoding Job must be written to an Asset, so let's create one. We use the delete flag to delete the blob and container if we delete the asset in MK.IO
_ = await CreateOutputAssetAsync(client, config["StorageName"]!, outputEncodedAssetName, $"encoded asset from {inputAssetName} using {_encodingTransformName} transform");
// Ensure that you have the desired encoding Transform. This is really a one time setup operation.
_ = await CreateOrUpdateTransformAsync(client, _encodingTransformName, _encodingPreset);
// Submit a job request to MK.IO to apply the specified Transform to a given input video.
_ = await SubmitJobAsync(client, _encodingTransformName, encodingJobName, inputAssetName, outputEncodedAssetName, _inputMP4FileName);
// Polls the status of the job and wait for it to finish.
var job = await WaitForJobToFinishAsync(client, _encodingTransformName, encodingJobName);
if (job.Properties.State != JobState.Finished)
{
// Alert the user if issue with the encoding job
DisplayJobStatusWhenCompleted(job);
await CleanIfUserAcceptsAsync(client, [inputAssetName, outputEncodedAssetName], [(_encodingTransformName, encodingJobName)]);
}
else
{
// VOD AI based transcription -------------------------------------------------------------------------------------------------------------------------------
// See https://docs.mk.io/docs/vod-transcription
// Create a transform for the VOD Transcription
_ = await CreateOrUpdateTransformVodTranscriptAsync(client, _vodTranscriptionTransformName);
// Create a new asset to store the generated VTT file (transcript)
_ = await CreateOutputAssetAsync(client, config["StorageName"]!, outputVTTAssetName);
// Submit a job request to MK.IO to apply the specified Transform to a given input video.
_ = await SubmitJobAsync(client, _vodTranscriptionTransformName, vodTranscriptionJobName, inputAssetName, outputVTTAssetName, _inputMP4FileName);
// Polls the status of the job and wait for it to finish.
_ = await WaitForJobToFinishAsync(client, _vodTranscriptionTransformName, vodTranscriptionJobName);
// WebVTT file inserted as text track -----------------------------------------------------------------------------------------------------------------------
// See https://docs.mk.io/docs/webvtt-subtitle-side-loading
// Create the transform to insert the VTT file as a text track
_ = await CreateOrUpdateTransformTextTrackAsync(client, _textTrackInsertionTransformName);
// Submit a job request to MK.IO to apply the specified Transform to a given input video.
_ = await SubmitJobAsync(client, _textTrackInsertionTransformName, textTrackInsertionJobName, outputVTTAssetName, outputEncodedAssetName, Path.GetFileNameWithoutExtension(_inputMP4FileName) + ".vtt");
// Polls the status of the job and wait for it to finish.
_ = await WaitForJobToFinishAsync(client, _textTrackInsertionTransformName, textTrackInsertionJobName);
// Thumbnails sprite generation -----------------------------------------------------------------------------------------------------------------------------
// See https://docs.mk.io/docs/thumbnails-generation
// Output asset to host the thumbnail.
_ = await CreateOutputAssetAsync(client, config["StorageName"]!, outputThumbnailAssetName, $"Thumbnail asset from {outputEncodedAssetName} using {_thumbnailTransformName} transform");
// Ensure that you have the desired encoding Transform. This is really a one time setup operation.
_ = await CreateOrUpdateThumbnailTransformAsync(client, _thumbnailTransformName);
// Submit a job request to MK.IO to apply the specified Transform to a given input video.
_ = await SubmitJobAsync(client, _thumbnailTransformName, thumbnailJobName, outputEncodedAssetName, outputThumbnailAssetName, Path.GetFileNameWithoutExtension(_inputMP4FileName) + ".ism");
// Polls the status of the job and wait for it to finish.
var thumbnailJob = await WaitForJobToFinishAsync(client, _thumbnailTransformName, thumbnailJobName);
if (thumbnailJob.Properties.State == JobState.Finished)
{
// Create a locator for clear streaming
_ = await CreateDownloadLocatorAsync(client, outputThumbnailAssetName, locatorThumbnailName);
// Display download paths
await ListDownloadUrlsAsync(client, locatorThumbnailName);
}
// Publishing video asset -----------------------------------------------------------------------------------------------------------------------------------
// Create a locator for clear streaming
_ = await CreateStreamingLocatorAsync(client, outputEncodedAssetName, locatorName);
// List the streaming endpoint(s) and propose creation if needed
var createdEndpoint = await ListStreamingEndpointsAndCreateOneIfNeededAsync(client);
// Display streaming paths and test player urls
await ListStreamingUrlsAsync(client, locatorName);
// Cleanign assets-------------------------------------------------------------------------------------------------------------------------------------------
await CleanIfUserAcceptsAsync(client,
[inputAssetName, outputEncodedAssetName, outputVTTAssetName, outputThumbnailAssetName],
[(_encodingTransformName, encodingJobName), (_vodTranscriptionTransformName, vodTranscriptionJobName), (_textTrackInsertionTransformName, textTrackInsertionJobName), (_thumbnailTransformName, thumbnailJobName)],
createdEndpoint);
}
}
/// <summary>
/// Does the settings loading and checking.
/// </summary>
/// <returns>Configuration.</returns>
/// <exception cref="Exception"></exception>
private static IConfigurationRoot LoadAndCheckSettings()
{
// Build a config object, using env vars and JSON providers.
IConfigurationRoot config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables()
.Build();
// Checking settings
if (string.IsNullOrEmpty(config["MKIOSubscriptionName"]) || string.IsNullOrEmpty(config["MKIOToken"]) || string.IsNullOrEmpty(config["StorageName"]))
{
Console.WriteLine("Missing MKIOSubscriptionName, MKIOToken, or StorageName in configuration file.");
throw new Exception("Missing mandatory configuration settings.");
}
Console.WriteLine($"Using '{config["MKIOSubscriptionName"]!}' MK.IO subscription.");
return config;
}
/// <summary>
/// Creates a new input Asset and uploads the specified local video file into it.
/// </summary>
/// <param name="client">The MK.IO client.</param>
/// <param name="storageName">The storage name.</param>
/// <param name="tenantId">The Azure Tenant Id</param>
/// <param name="assetName">The asset name.</param>
/// <param name="fileToUpload">The file you want to upload into the asset.</param>
/// <returns>The asset.</returns>
private static async Task<AssetSchema> CreateInputAssetAsync(MKIOClient client, string storageName, string tenantId, string assetName, string? description = null)
{
// Create an input asset
var inputAsset = await client.Assets.CreateOrUpdateAsync(
assetName,
null,
storageName!,
description,
AssetContainerDeletionPolicyType.Delete,
null,
new Dictionary<string, string> { { "typeAsset", "source" } }
);
Console.WriteLine($"Input asset '{inputAsset.Name}' created.");
return inputAsset;
}
/// <summary>
/// Creates a new input Asset and uploads the specified local video file into it.
/// </summary>
/// <param name="client">The MK.IO client.</param>
/// <param name="storageName">The storage name.</param>
/// <param name="tenantId">The Azure Tenant Id</param>
/// <param name="assetName">The asset name.</param>
/// <param name="fileToUpload">The file you want to upload into the asset.</param>
/// <returns>The asset.</returns>
private static async Task<AssetSchema> CreateInputAssetAndUploadFileAsync(MKIOClient client, string storageName, string tenantId, string assetName, string fileToUpload)
{
var inputAsset = await CreateInputAssetAsync(client, storageName, tenantId, assetName, $"input asset {fileToUpload}");
// We wait 2 seconds to let time to MK.IO create the container
await Task.Delay(2000);
// Create an interactive browser credential which will use the system authentication broker
var blobContainerClient = new BlobContainerClient(
new Uri($"https://{inputAsset.Properties.StorageAccountName}.blob.core.windows.net/{inputAsset.Properties.Container}"),
new InteractiveBrowserCredential(new InteractiveBrowserCredentialOptions()
{
TenantId = tenantId
}
)
);
// User or app must have Storage Blob Data Contributor on the account for the upload to work!
// Upload a blob (e.g., from a local file)
var blobClient = blobContainerClient.GetBlobClient(Path.GetFileName(fileToUpload));
await blobClient.UploadAsync(fileToUpload);
Console.WriteLine($"File '{fileToUpload}' uploaded to input asset.");
return inputAsset;
}
/// <summary>
/// Creates an ouput asset. The output from the encoding Job must be written to an Asset.
/// </summary>
/// <param name="client">The MK.IO client.</param>
/// <param name="storageName">The storage name.</param>
/// <param name="assetName">The asset name.</param>
/// <param name="description">The description of the asset.</param>
/// <returns>The asset.</returns>
private static async Task<AssetSchema> CreateOutputAssetAsync(MKIOClient client, string storageName, string assetName, string? description = null)
{
// Create an empty output asset
var outputAsset = await client.Assets.CreateOrUpdateAsync(
assetName,
null,
storageName!,
description,
AssetContainerDeletionPolicyType.Delete,
null,
new Dictionary<string, string> { { "typeAsset", "encoded" } }
);
Console.WriteLine($"Output asset '{assetName}' created.");
return outputAsset;
}
/// <summary>
/// Creates or updates the Transform.
/// </summary>
/// <param name="client">The MK.IO client.</param>
/// <param name="transformName">The transform name.</param>
/// <param name="encoderPreset">The encoder preset.</param>
/// <returns>The transform.</returns>
private static async Task<TransformSchema> CreateOrUpdateTransformAsync(MKIOClient client, string transformName, EncoderNamedPreset encoderPreset)
{
// Create or update a transform
var transform = await client.Transforms.CreateOrUpdateAsync(transformName, new TransformProperties
{
Description = $"Encoding with {encoderPreset} preset",
Outputs =
[
new() {
Preset = new BuiltInStandardEncoderPreset(encoderPreset),
RelativePriority = TransformOutputPriorityType.Normal
}
]
});
Console.WriteLine($"Transform '{transform.Name}' created/updated.");
return transform;
}
/// <summary>
/// Creates or updates the text track insertion Transform.
/// </summary>
/// <param name="client">The MK.IO client.</param>
/// <param name="transformName">The transform name.</param>
/// <returns>The transform.</returns>
private static async Task<TransformSchema> CreateOrUpdateTransformTextTrackAsync(MKIOClient client, string transformName)
{
// https://docs.mk.io/docs/add-a-track-to-a-vod-asset
var trackInserter = new TextTrack()
{
DisplayName = "English",
LanguageCode = "en-US",
TrackName = "English",
PlayerVisibility = TextTrackPlayerVisibility.Visible,
HlsSettings = new HlsSettings()
{
Characteristics = "public.accessibility.transcribes-spoken-dialog",
Default = true,
Forced = false
}
};
// Create or update a transform
var transform = await client.Transforms.CreateOrUpdateAsync(transformName, new TransformProperties
{
Description = $"Text track inserter transform",
Outputs =
[
new() {
Preset = new TrackInserterPreset([trackInserter]),
RelativePriority = TransformOutputPriorityType.Normal
}
]
});
Console.WriteLine($"Transform '{transform.Name}' created/updated.");
return transform;
}
/// <summary>
/// Creates or updates the VOD Transcript Transform.
/// </summary>
/// <param name="client">The MK.IO client.</param>
/// <param name="transformName">The transform name.</param>
/// <returns>The transform.</returns>
private static async Task<TransformSchema> CreateOrUpdateTransformVodTranscriptAsync(MKIOClient client, string transformName)
{
// settings
var pipelineArgs = new VodPipelineArguments(
new VodArguments(
new List<Transcription> {
new("language", "en-US")
}
));
// Create or update a transform
var transform = await client.Transforms.CreateOrUpdateAsync(transformName, new TransformProperties
{
Description = $"VOD Transcript transform",
Outputs =
[
new() {
Preset = new AIPipelinePreset(pipelineArgs),
RelativePriority = TransformOutputPriorityType.Normal
}
]
});
Console.WriteLine($"Transform '{transform.Name}' created/updated.");
return transform;
}
/// <summary>
/// Creates or updates the Transform for thumbnail creation.
/// </summary>
/// <param name="client">The MK.IO client.</param>
/// <param name="transformName">The transform name.</param>
/// <returns>The transform.</returns>
private static async Task<TransformSchema> CreateOrUpdateThumbnailTransformAsync(MKIOClient client, string transformName)
{
// https://docs.mk.io/docs/thumbnails-generation
// Sprite configuration
var thumbnailConfig = new List<ThumbnailGeneratorConfiguration>
{
new() {
Format = "Jpeg",
Start = "PT0S",
Range = "100%",
Step = "1%",
Width = "10%",
Height = "10%",
SpriteColumn = 10
}
};
// Create or update a transform
var transform = await client.Transforms.CreateOrUpdateAsync(transformName, new TransformProperties
{
Description = $"Thumbnail transform",
Outputs =
[
new() {
Preset = new ThumbnailGeneratorPreset(thumbnailConfig),
RelativePriority = TransformOutputPriorityType.Normal
}
]
});
Console.WriteLine($"Transform '{transform.Name}' created/updated.");
return transform;
}
/// <summary>
/// Submits a request to MK.IO to apply the specified Transform to a given input video.
/// </summary>
/// <param name="client">The MK.IO client.</param>
/// <param name="transformName">The transform name.</param>
/// <param name="jobName">The job name.</param>
/// <param name="inputAssetName">The input asset name.</param>
/// <param name="outputAssetName">The output asset name.</param>
/// <param name="fileName">The filename in the input asset name.</param>
/// <returns>The job.</returns>
private static async Task<JobSchema> SubmitJobAsync(MKIOClient client, string transformName, string jobName, string inputAssetName, string outputAssetName, string? inputFileName)
{
// Create the encoding job
var encodingJob = await client.Jobs.CreateAsync(
transformName,
jobName,
new JobProperties
{
Description = $"My job which encodes '{inputAssetName}' to '{outputAssetName}' with '{transformName}' transform.",
Priority = JobPriorityType.Normal,
Input = new JobInputAsset(
inputAssetName,
[
inputFileName != null ? Path.GetFileName(inputFileName): ""
]),
Outputs =
[
new JobOutputAsset()
{
AssetName = outputAssetName
}
]
}
);
Console.WriteLine($"Processing job '{encodingJob.Name}' submitted.");
return encodingJob;
}
/// <summary>
/// Creates a streaming locator on the asset.
/// </summary>
/// <param name="client">The MK.IO client.</param>
/// <param name="outputAssetName">The output asset name.</param>
/// <param name="locatorName">The locator name.</param>
/// <returns>The streaming locator.</returns>
private static async Task<StreamingLocatorSchema> CreateStreamingLocatorAsync(MKIOClient client, string outputAssetName, string locatorName)
{
return await client.StreamingLocators.CreateAsync(
locatorName,
new StreamingLocatorProperties
{
AssetName = outputAssetName,
StreamingPolicyName = PredefinedStreamingPolicy.ClearStreamingOnly
});
}
/// <summary>
/// Lists the streaming endpoint(s) and proposes to create one if there is none.
/// </summary>
/// <param name="client">The MK.IO client.</param>
/// <returns>The name of the streaming endpoint created, otherwise null.</returns>
private static async Task<string?> ListStreamingEndpointsAndCreateOneIfNeededAsync(MKIOClient client)
{
string? createdStreamingEndpointName = null;
var streamingEndpoints = await client.StreamingEndpoints.ListAsync();
if (streamingEndpoints.Any())
{
Console.WriteLine("Streaming endpoints:");
foreach (var streamingEndpoint in streamingEndpoints)
{
Console.WriteLine($" {streamingEndpoint.Name} ({streamingEndpoint.Properties.ResourceState})");
}
Console.WriteLine();
}
else
{
string? response;
do
{
Console.WriteLine("No streaming endpoint found. Do you want to create one and start it? (y/n)");
response = Console.ReadLine();
} while (response != "Y" && response != "N" && response != "y" && response != "n");
if (response == "Y" || response == "y")
{
var locationToUse = await client.Account.GetSubscriptionLocationAsync();
if (locationToUse != null)
{
var streamingEndpoint = await client.StreamingEndpoints.CreateAsync(
MKIOClient.GenerateUniqueName("endpoint"),
locationToUse.Name,
new StreamingEndpointProperties
{
Description = "Streaming endpoint created by sample"
},
true
);
createdStreamingEndpointName = streamingEndpoint.Name;
Console.WriteLine($"Streaming endpoint '{streamingEndpoint.Name}' created and starting.");
}
else
{
Console.WriteLine("Error. No location found. Cannot create the streaming endpoint.");
}
Console.WriteLine();
}
}
return createdStreamingEndpointName;
}
/// <summary>
/// Lists the streaming Urls for a specified locator name.
/// </summary>
/// <param name="client">The MK.IO client.</param>
/// <param name="locatorName">The locator name.</param>
/// <returns></returns>
private static async Task ListStreamingUrlsAsync(MKIOClient client, string locatorName)
{
// list Streaming Endpoints
var streamingEndpoints = await client.StreamingEndpoints.ListAsync();
// List the streaming Url
var paths = await client.StreamingLocators.ListUrlPathsAsync(locatorName);
Console.WriteLine($"Streaming paths for locator '{locatorName}':");
foreach (var path in paths.StreamingPaths)
{
Console.WriteLine($" Streaming protocol : {path.StreamingProtocol}");
foreach (var p in path.Paths)
{
foreach (var se in streamingEndpoints)
{
Console.WriteLine($" Url : https://{se.Properties.HostName}{p}");
Console.WriteLine($" Test player url: " + string.Format(_bitmovinPlayer, path.StreamingProtocol.ToString().ToLower(), Uri.EscapeDataString("https://" + se.Properties.HostName + p)));
}
}
Console.WriteLine();
}
}
/// <summary>
/// Polls MK.IO for the status of the Job.
/// </summary>
/// <param name="client">The MK.IO client.</param>
/// <param name="transformName">The transform name.</param>
/// <param name="jobName">The job name.</param>
/// <returns>The job when processing is finished/failed/cancelled.</returns>
private static async Task<JobSchema> WaitForJobToFinishAsync(MKIOClient client, string transformName, string jobName)
{
Console.WriteLine();
const int SleepIntervalMs = 10 * 1000;
JobSchema job;
do
{
await Task.Delay(SleepIntervalMs);
job = await client.Jobs.GetAsync(transformName, jobName);
Console.WriteLine($"State: {job.Properties.State}" + (job.Properties.Outputs.First().Progress != null ? $" Progress: {job.Properties.Outputs.First().Progress}%" : string.Empty));
}
while (job.Properties.State == JobState.Queued || job.Properties.State == JobState.Scheduled || job.Properties.State == JobState.Processing);
Console.WriteLine();
return job;
}
/// <summary>
/// Display information about a job completed (finished, cancelled or failed).
/// </summary>
/// <param name="job">The job which is finished.</param>
private static void DisplayJobStatusWhenCompleted(JobSchema job)
{
if (job.Properties.State == JobState.Error)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Job failed.");
if (job.Properties.Outputs.First() != null && job.Properties.Outputs.First().Error.Message != null)
{
Console.WriteLine(job.Properties.Outputs.First().Error.Message);
}
}
else if (job.Properties.State == JobState.Canceled)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Job cancelled.");
}
else if (job.Properties.State == JobState.Finished)
{
Console.WriteLine("Job finished.");
}
Console.ResetColor();
}
/// <summary>
/// Creates a download locator on the asset.
/// </summary>
/// <param name="client">The MK.IO client.</param>
/// <param name="outputAssetName">The output asset name.</param>
/// <param name="locatorName">The locator name.</param>
/// <returns>The streaming locator.</returns>
private static async Task<StreamingLocatorSchema> CreateDownloadLocatorAsync(MKIOClient client, string outputAssetName, string locatorName)
{
return await client.StreamingLocators.CreateAsync(
locatorName,
new StreamingLocatorProperties
{
AssetName = outputAssetName,
StreamingPolicyName = PredefinedStreamingPolicy.DownloadOnly
});
}
/// <summary>
/// Lists the download Urls for a specified locator name.
/// </summary>
/// <param name="client">The MK.IO client.</param>
/// <param name="locatorName">The locator name.</param>
/// <returns></returns>
private static async Task ListDownloadUrlsAsync(MKIOClient client, string locatorName)
{
// list Streaming Endpoints
var streamingEndpoints = await client.StreamingEndpoints.ListAsync();
// List the streaming Url
var paths = await client.StreamingLocators.ListUrlPathsAsync(locatorName);
Console.WriteLine($"Download Urls for locator '{locatorName}' :");
foreach (var path in paths.DownloadPaths)
{
foreach (var se in streamingEndpoints)
{
Console.WriteLine($" Url : https://{se.Properties.HostName}{path}");
}
Console.WriteLine();
}
}
/// <summary>
/// Cleans the created resources if user accepts.
/// </summary>
/// <param name="client"></param>
/// <param name="assetNames"></param>
/// <param name="transformAndjobNames"></param>
/// <param name="streamingEndpoint"></param>
/// <returns></returns>
private static async Task CleanIfUserAcceptsAsync(MKIOClient client, List<string> assetNames, List<(string, string)> transformAndjobNames, string? streamingEndpoint = null)
{
string? response;
do
{
Console.WriteLine("Do you want to clean the created resources (assets, job, etc) ? (y/n)");
response = Console.ReadLine();
} while (response != "Y" && response != "N" && response != "y" && response != "n");
if (response == "Y" || response == "y")
{
foreach (var assetName in assetNames)
{
try
{
await client.Assets.DeleteAsync(assetName);
}
catch (Exception ex)
{
Console.WriteLine($"Unexpected error deleting asset '{assetName}'. Error: {ex.Message}");
}
}
foreach (var transformAndjobName in transformAndjobNames)
{
try
{
await client.Jobs.DeleteAsync(transformAndjobName.Item1, transformAndjobName.Item2);
}
catch (Exception ex)
{
Console.WriteLine($"Error deleting job '{transformAndjobName.Item2}'. Error: {ex.Message}");
}
try
{
await client.Transforms.DeleteAsync(transformAndjobName.Item1);
}
catch (Exception ex)
{
Console.WriteLine($"Error deleting transform '{transformAndjobName.Item1}'. Error: {ex.Message}");
}
}
if (streamingEndpoint != null)
try
{
await client.StreamingEndpoints.DeleteAsync(streamingEndpoint);
}
catch (Exception ex)
{
Console.WriteLine($"Error deleting streaming endpoint '{streamingEndpoint}'. Error: {ex.Message}");
}
Console.WriteLine("Cleaning done.");
}
}
}
}