Exemple #1
0
        public async Task <IList <string> > ProcessMovieAsync(Stream stream, string inputMP4FileName)
        {
            IList <string>            urls   = new List <string>();
            IAzureMediaServicesClient client = await CreateMediaServicesClientAsync();

            client.LongRunningOperationRetryTimeout = 2;

            string uniqueness      = Guid.NewGuid().ToString("N");
            string jobName         = $"job-{uniqueness}";
            string locatorName     = $"locator-{uniqueness}";
            string outputAssetName = $"output-{uniqueness}";
            string inputAssetName  = $"input-{uniqueness}";
            // Ensure that you have the desired encoding Transform. This is really a one time setup operation.
            Transform transform = await GetOrCreateTransformAsync(client, this.AzureMediaServicesSettings.ResourceGroup, this.AzureMediaServicesSettings.MediaServiceAccountName, AdaptiveStreamingTransformName);

            await CreateInputAssetAsync(client, this.AzureMediaServicesSettings.ResourceGroup, this.AzureMediaServicesSettings.MediaServiceAccountName, inputAssetName, inputMP4FileName, stream);

            Asset outputAsset = await CreateOutputAssetAsync(client, this.AzureMediaServicesSettings.ResourceGroup, this.AzureMediaServicesSettings.MediaServiceAccountName, outputAssetName);

            Job job = await SubmitJobAsync(client, this.AzureMediaServicesSettings.ResourceGroup, this.AzureMediaServicesSettings.MediaServiceAccountName, AdaptiveStreamingTransformName, jobName, inputAssetName, outputAsset.Name);

            job = await WaitForJobToFinishAsync(client, this.AzureMediaServicesSettings.ResourceGroup, this.AzureMediaServicesSettings.MediaServiceAccountName, AdaptiveStreamingTransformName, jobName);

            if (job.State == JobState.Finished)
            {
                StreamingLocator locator = await CreateStreamingLocatorAsync(client, this.AzureMediaServicesSettings.ResourceGroup, this.AzureMediaServicesSettings.MediaServiceAccountName, outputAsset.Name, locatorName);

                urls = await GetStreamingUrlsAsync(client, this.AzureMediaServicesSettings.ResourceGroup, this.AzureMediaServicesSettings.MediaServiceAccountName, locator.Name);
            }

            return(urls);
        }
        public StreamingLocator CreateLocator(string locatorName, string assetName, string streamingPolicyName, ContentProtection contentProtection)
        {
            StreamingLocator locator = _media.StreamingLocators.Get(MediaAccount.ResourceGroupName, MediaAccount.Name, locatorName);

            if (locator == null)
            {
                string contentKeyPolicyName = null;
                if (streamingPolicyName == PredefinedStreamingPolicy.ClearKey)
                {
                    CreateContentKeyPolicyAES();
                    contentKeyPolicyName = Constant.Media.ContentKey.PolicyAES;
                }
                else if (streamingPolicyName == PredefinedStreamingPolicy.SecureStreaming)
                {
                    CreateContentKeyPolicyDRM(contentProtection);
                    contentKeyPolicyName = Constant.Media.ContentKey.PolicyDRM;
                }
                locator = new StreamingLocator(assetName, streamingPolicyName)
                {
                    DefaultContentKeyPolicyName = contentKeyPolicyName
                };
                locator = _media.StreamingLocators.Create(MediaAccount.ResourceGroupName, MediaAccount.Name, locatorName, locator);
            }
            return(locator);
        }
        public string GetStreamingUrl(StreamingLocator streamingLocator, string fileName)
        {
            UriBuilder uriBuilder = new UriBuilder()
            {
                Scheme = Constant.Media.Stream.DefaultScheme,
                Host   = GetStreamingHost(null)
            };
            ListPathsResponse paths = _media.StreamingLocators.ListPaths(MediaAccount.ResourceGroupName, MediaAccount.Name, streamingLocator.Name);

            if (!string.IsNullOrEmpty(fileName))
            {
                foreach (string downloadPath in paths.DownloadPaths)
                {
                    if (downloadPath.Contains(fileName))
                    {
                        uriBuilder.Path = downloadPath;
                    }
                }
            }
            else
            {
                foreach (StreamingPath streamingPath in paths.StreamingPaths)
                {
                    if (streamingPath.StreamingProtocol == StreamingPolicyStreamingProtocol.SmoothStreaming && streamingPath.Paths.Count == 1)
                    {
                        uriBuilder.Path = streamingPath.Paths[0];
                    }
                }
                uriBuilder.Path = string.Concat(uriBuilder.Path, Constant.Media.Stream.DefaultFormat);
            }
            return(uriBuilder.ToString());
        }
Exemple #4
0
        private static MediaStream GetMediaStream(string authToken, MediaClient mediaClient, Asset asset, AssetFilter assetFilter,
                                                  StreamingLocator locator, string playerUrl)
        {
            string        streamId   = assetFilter != null ? assetFilter.Id : asset.AssetId.ToString();
            string        streamName = assetFilter != null ? assetFilter.Name : locator.Name;
            MediaClipType streamType = assetFilter != null ? MediaClipType.Filter : MediaClipType.Asset;

            if (streamType == MediaClipType.Filter)
            {
                playerUrl = string.Concat(playerUrl, "(filter=", assetFilter.Name, ")");
            }
            MediaStream mediaStream = new MediaStream()
            {
                Id          = streamId,
                Name        = streamName,
                Type        = streamType,
                Description = asset.Description,
                Source      = new StreamSource()
                {
                    Url            = playerUrl,
                    ProtectionInfo = mediaClient.GetProtectionInfo(authToken, mediaClient, locator)
                },
                TextTracks     = Track.GetTextTracks(mediaClient, asset),
                ThumbnailUrls  = GetThumbnailUrls(mediaClient, locator),
                ContentInsight = GetMediaInsight(mediaClient, asset)
            };

            return(mediaStream);
        }
        public async Task <string> AMS_StreamingURL(
            [ActivityTrigger] IDurableActivityContext activityContext,
            ILogger log)
        {
            string inputValue = activityContext.GetInput <string>();
            var    data       = JsonConvert.DeserializeObject <ConfigAssetDTO>(inputValue);
            var    assetAMS   = await _amsService.GetAssetAMS(data.AssetID);

            var ams = await GetAmsCredential(log);

            IAzureMediaServicesClient client = ams.Client;

            var listUrl = new List <string>();
            StreamingLocator locator = await _amsService.CreateStreamingLocatorAsync(client, ams.ResourceGroup, ams.AccountName, data.OutputName, data.LocatorName);

            IList <string> urls = await _amsService.GetStreamingUrlsAsync(client, ams.ResourceGroup, ams.AccountName, locator.Name);

            foreach (var url in urls)
            {
                listUrl.Add(url);
            }

            string listStreamingURL = string.Join(",", listUrl.ToArray());

            assetAMS.StreamingUrl = listStreamingURL;
            await _amsService.UpdateAssetAMS(data.AssetID, assetAMS);

            return(listStreamingURL);
        }
        public StreamingLocator GetStreamingLocator(string locatorName, string assetName, string streamingPolicyName, ContentProtection contentProtection)
        {
            StreamingLocator streamingLocator = _media.StreamingLocators.Get(MediaAccount.ResourceGroupName, MediaAccount.Name, locatorName);

            if (streamingLocator == null)
            {
                string contentKeyPolicyName = null;
                if (string.IsNullOrEmpty(streamingPolicyName))
                {
                    streamingPolicyName = PredefinedStreamingPolicy.DownloadAndClearStreaming;
                }
                else if (streamingPolicyName == PredefinedStreamingPolicy.ClearKey)
                {
                    contentKeyPolicyName = Constant.Media.ContentKeyPolicy.Aes;
                    CreateContentKeyPolicyAes(contentKeyPolicyName);
                }
                else if (streamingPolicyName == PredefinedStreamingPolicy.MultiDrmStreaming)
                {
                    contentKeyPolicyName = Constant.Media.ContentKeyPolicy.Drm;
                    CreateContentKeyPolicyDrm(contentKeyPolicyName, contentProtection);
                }
                else if (streamingPolicyName == PredefinedStreamingPolicy.MultiDrmCencStreaming)
                {
                    contentKeyPolicyName = Constant.Media.ContentKeyPolicy.DrmCenc;
                    CreateContentKeyPolicyDrm(contentKeyPolicyName, contentProtection);
                }
                streamingLocator = new StreamingLocator(assetName, streamingPolicyName)
                {
                    DefaultContentKeyPolicyName = contentKeyPolicyName
                };
                streamingLocator = _media.StreamingLocators.Create(MediaAccount.ResourceGroupName, MediaAccount.Name, locatorName, streamingLocator);
            }
            return(streamingLocator);
        }
Exemple #7
0
        private async Task <StreamingLocator> CreateStreamingLocatorAsync(
            string resourceGroup,
            string accountName,
            string assetName,
            string locatorName)
        {
            StreamingLocator locator = null;

            try
            {
                locator = await client.StreamingLocators.CreateAsync(
                    resourceGroup,
                    accountName,
                    locatorName,
                    new StreamingLocator
                {
                    AssetName           = assetName,
                    StreamingPolicyName = PredefinedStreamingPolicy.ClearStreamingOnly
                });
            }
            catch (ApiErrorException apiError)
            {
            }


            return(locator);
        }
        public async Task <string> GetStreamingUrlAsync(string assetName)
        {
            string streamingUrl = null;

            try
            {
                StreamingLocator sl = GetStreamingLocator(assetName);
                if (sl == null)
                {
                    DateTime sTime       = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                    long     epoch       = (long)(DateTime.Now - sTime).TotalSeconds;
                    string   locatorName = "locator_" + epoch.ToString();

                    sl = await CreateStreamingLocatorAsync(locatorName, assetName);
                }

                StreamingEndpoint sep = await GetDefaultStreamingEndpointAsync();

                streamingUrl = "https://" + sep.HostName + "/" + sl.StreamingLocatorId + "/content.ism/manifest";
            }
            catch (Exception)
            {
            }

            return(streamingUrl);
        }
Exemple #9
0
 public JsonResult Publish(string entityName, bool unpublish)
 {
     try
     {
         string message;
         string authToken = HomeController.GetAuthToken(Request, Response);
         using (MediaClient mediaClient = new MediaClient(authToken))
         {
             if (unpublish)
             {
                 mediaClient.DeleteLocators(entityName);
                 message = string.Format(Constant.Message.AssetUnpublished, entityName);
             }
             else
             {
                 Asset            asset = mediaClient.GetEntity <Asset>(MediaEntity.Asset, entityName);
                 string           streamingPolicyName = PredefinedStreamingPolicy.DownloadAndClearStreaming;
                 StreamingLocator streamingLocator    = mediaClient.GetStreamingLocator(asset.Name, asset.Name, streamingPolicyName, null);
                 message = mediaClient.GetStreamingUrl(streamingLocator, null);
             }
         }
         return(Json(message));
     }
     catch (ApiErrorException ex)
     {
         return(new JsonResult(ex.Response.Content)
         {
             StatusCode = (int)ex.Response.StatusCode
         });
     }
 }
        public string GetDownloadUrl(Asset asset, string fileName)
        {
            string           streamingPolicyName = PredefinedStreamingPolicy.DownloadOnly;
            StreamingLocator locator             = CreateLocator(streamingPolicyName, asset.Name, streamingPolicyName, null);
            string           relativePath        = string.Concat("/", locator.StreamingLocatorId, "/", fileName);

            return(GetDefaultUrl(relativePath));
        }
Exemple #11
0
        private void PublishDownloadAsset(IAzureMediaServicesClient client, string resourceGroup, string accountName, string assetName, string streamingLocatorName)
        {
            StreamingLocator locator = new StreamingLocator(
                assetName: assetName,
                streamingPolicyName: PredefinedStreamingPolicy.DownloadOnly);

            client.StreamingLocators.Create(resourceGroup, accountName, streamingLocatorName, locator);
        }
        /// <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 = await CreateMediaServicesClientAsync(config);

            // 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}";
            string inputAssetName  = $"input-{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);

            // Create a new input Asset and upload the specified local video file into it.
            await CreateInputAssetAsync(client, config.ResourceGroup, config.AccountName, inputAssetName, InputMP4FileName);

            // Use the name of the created input asset to create the job input.
            JobInput jobInput = new JobInputAsset(assetName: inputAssetName);

            // 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, jobName, inputAssetName, outputAsset.Name);

            // 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)
            {
                Console.WriteLine("Job finished.");
                if (!Directory.Exists(OutputFolderName))
                {
                    Directory.CreateDirectory(OutputFolderName);
                }

                await DownloadOutputAssetAsync(client, config.ResourceGroup, config.AccountName, outputAsset.Name, OutputFolderName);

                StreamingLocator locator = await CreateStreamingLocatorAsync(client, config.ResourceGroup, config.AccountName, outputAsset.Name, locatorName);

                IList <string> urls = await GetStreamingUrlsAsync(client, config.ResourceGroup, config.AccountName, locator.Name);

                foreach (var url in urls)
                {
                    Console.WriteLine(url);
                }
            }

            Console.WriteLine("Done. Copy and paste the Streaming URL into the Azure Media Player at 'http://aka.ms/azuremediaplayer'.");
        }
Exemple #13
0
 internal static void ValidateLocator(StreamingLocator locator, string expectedName, string expectedAssetName, string expectedDefaultContentKeyPolicyName, string expectedStreamingPolicyName)
 {
     Assert.Equal(expectedAssetName, locator.AssetName);
     Assert.Equal(expectedName, locator.Name);
     Assert.Equal(expectedDefaultContentKeyPolicyName, locator.DefaultContentKeyPolicyName);
     Assert.NotEqual(Guid.Empty, locator.StreamingLocatorId);
     Assert.Equal(expectedStreamingPolicyName, locator.StreamingPolicyName);
     Assert.False(string.IsNullOrEmpty(locator.Id));
 }
        /// <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>
        async Task <string> IUploadEncodeAndStreamFiles.RunAsync(ConfigWrapper config, string blobName)
        {
            string urlStream = "";
            IAzureMediaServicesClient client = await(this as IUploadEncodeAndStreamFiles).CreateMediaServicesClientAsync(config);

            // 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}";
            string inputAssetName  = $"input-{uniqueness}";

            // Ensure that you have the desired encoding Transform. This is really a one time setup operation.
            Transform transform = await(this as IUploadEncodeAndStreamFiles).GetOrCreateTransformAsync(client, config.ResourceGroup, config.AccountName, AdaptiveStreamingTransformName);

            string path_project_bin = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location.Substring(0, Assembly.GetEntryAssembly().Location.IndexOf("bin\\")));

            // Create a new input Asset and upload the specified local video file into it.
            await(this as IUploadEncodeAndStreamFiles).CreateInputAssetAsync(client, config.ResourceGroup, config.AccountName, inputAssetName, path_project_bin + "/bin/file-test/test-decrypt" + blobName);

            // Use the name of the created input asset to create the job input.
            JobInput jobInput = new JobInputAsset(assetName: inputAssetName);

            // Output from the encoding Job must be written to an Asset, so let's create one
            Asset outputAsset = await(this as IUploadEncodeAndStreamFiles).CreateOutputAssetAsync(client, config.ResourceGroup, config.AccountName, outputAssetName);

            Job job = await(this as IUploadEncodeAndStreamFiles).SubmitJobAsync(client, config.ResourceGroup, config.AccountName, AdaptiveStreamingTransformName, jobName, inputAssetName, outputAsset.Name);

            // 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(this as IUploadEncodeAndStreamFiles).WaitForJobToFinishAsync(client, config.ResourceGroup, config.AccountName, AdaptiveStreamingTransformName, jobName);

            if (job.State == JobState.Finished)
            {
                Console.WriteLine("Job finished.");

                StreamingLocator locator = await(this as IUploadEncodeAndStreamFiles).CreateStreamingLocatorAsync(client, config.ResourceGroup, config.AccountName, outputAsset.Name, locatorName);

                IList <string> urls = await(this as IUploadEncodeAndStreamFiles).GetStreamingUrlsAsync(client, config.ResourceGroup, config.AccountName, locator.Name);
                foreach (var url in urls)
                {
                    urlStream = url;
                }
            }


            File.Delete(path_project_bin + "/bin/file-test/test-decrypt" + blobName);
            return(urlStream);

            //Console.WriteLine("Done. Copy and paste the Streaming URL into the Azure Media Player at 'http://aka.ms/azuremediaplayer'.");
        }
Exemple #15
0
        private async Task <StreamingLocator> CreateStreamingLocatorAsync(IAzureMediaServicesClient client, string resourceGroup, string accountName, string assetName, string locatorName)
        {
            StreamingLocator locator = await client.StreamingLocators.CreateAsync(resourceGroup, accountName, locatorName,
                                                                                  new StreamingLocator
            {
                AssetName           = assetName,
                StreamingPolicyName = PredefinedStreamingPolicy.ClearStreamingOnly
            });

            return(locator);
        }
Exemple #16
0
        private StreamingLocator PublishDownloadAsset(IAzureMediaServicesClient client, string resourceGroup, string accountName, string assetName, Guid streamingLocatorId)
        {
            string           streamingLocatorName = AnalyticsStreamingLocatorPrefix + streamingLocatorId.ToString();
            StreamingLocator locator = new StreamingLocator(
                assetName: assetName,
                streamingLocatorId: streamingLocatorId,
                streamingPolicyName: PredefinedStreamingPolicy.DownloadOnly
                );

            return(client.StreamingLocators.Create(resourceGroup, accountName, streamingLocatorName, locator));
        }
        static void Main(string[] args)
        {
            ConfigWrapper config = new ConfigWrapper();

            try{
                IAzureMediaServicesClient client = CreateMediaServicesClient(config);

                Transform transform = EnsureTransformExists(client, config.ResourceGroup, config.AccountName, AdaptiveStreamingTransformName);

                // 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().Substring(0, 13);

                string jobName         = "job-" + uniqueness;
                string locatorName     = "locator-" + uniqueness;
                string outputAssetName = "output-" + uniqueness;
                string inputAssetName  = "input-" + uniqueness;

                CreateInputAsset(client, config.ResourceGroup, config.AccountName, inputAssetName, InputMP4FileName);

                JobInput jobInput = new JobInputAsset(assetName: inputAssetName);

                Asset outputAsset = client.Assets.CreateOrUpdate(config.ResourceGroup, config.AccountName, outputAssetName, new Asset());

                Job job = SubmitJob(client, config.ResourceGroup, config.AccountName, AdaptiveStreamingTransformName, jobName, jobInput, outputAssetName);

                job = WaitForJobToFinish(client, config.ResourceGroup, config.AccountName, AdaptiveStreamingTransformName, jobName);

                if (job.State == JobState.Finished)
                {
                    Console.WriteLine("Job finished.");
                    if (!Directory.Exists(OutputFolder))
                    {
                        Directory.CreateDirectory(OutputFolder);
                    }
                    DownloadResults(client, config.ResourceGroup, config.AccountName, outputAssetName, OutputFolder);

                    StreamingLocator locator = CreateStreamingLocator(client, config.ResourceGroup, config.AccountName, outputAsset.Name, locatorName);

                    IList <string> urls = GetStreamingURLs(client, config.ResourceGroup, config.AccountName, locator.Name);
                    foreach (var url in urls)
                    {
                        Console.WriteLine(url);
                    }
                }
            }
            catch (ApiErrorException ex)
            {
                Console.WriteLine("{0}", ex.Message);

                Console.WriteLine("Code: {0}", ex.Body.Error.Code);
                Console.WriteLine("Message: {0}", ex.Body.Error.Message);
            }
        }
        public IEnumerable <StreamingLocator> GetLocators(string assetName)
        {
            List <StreamingLocator>       locators    = new List <StreamingLocator>();
            ListStreamingLocatorsResponse locatorList = _media.Assets.ListStreamingLocators(MediaAccount.ResourceGroupName, MediaAccount.Name, assetName);

            foreach (AssetStreamingLocator streamingLocator in locatorList.StreamingLocators)
            {
                StreamingLocator locator = GetEntity <StreamingLocator>(MediaEntity.StreamingLocator, streamingLocator.Name);
                locators.Add(locator);
            }
            return(locators);
        }
Exemple #19
0
        private static void PublishAssetWithEnvelopeEncryption(IAzureMediaServicesClient client, string resourceGroup, string accountName, string assetName, string streamingLocatorName)
        {
            string           contentKeyPolicyName = "SharedContentKeyPolicyUsedByAllAssets";
            ContentKeyPolicy policy = EnsureContentKeyPolicyExists(client, resourceGroup, accountName, contentKeyPolicyName);

            StreamingLocator locator = new StreamingLocator(
                assetName: assetName,
                streamingPolicyName: PredefinedStreamingPolicy.ClearKey,
                defaultContentKeyPolicyName: contentKeyPolicyName);

            client.StreamingLocators.Create(resourceGroup, accountName, streamingLocatorName, locator);
        }
        public string GetDownloadUrl(string assetName, string fileName)
        {
            string assetNameSuffix = Constant.Media.Job.OutputAssetNameSuffix.AdaptiveStreaming;

            if (assetName.Contains(Constant.Media.Job.OutputAssetNameSuffix.ContentAwareEncoding))
            {
                assetNameSuffix = Constant.Media.Job.OutputAssetNameSuffix.ContentAwareEncoding;
            }
            string           locatorName         = assetName.Replace(assetNameSuffix, Constant.Media.Thumbnail.Download);
            string           streamingPolicyName = PredefinedStreamingPolicy.DownloadOnly;
            StreamingLocator streamingLocator    = GetStreamingLocator(locatorName, assetName, streamingPolicyName, null);

            return(GetStreamingUrl(streamingLocator, fileName));
        }
Exemple #21
0
        public MediaPublishNotification PublishJobOutput(string transformName, string jobName, string eventType)
        {
            MediaPublishNotification publishNotification = new MediaPublishNotification
            {
                PhoneNumber   = this.UserAccount.MobilePhoneNumber,
                StatusMessage = string.Format(Constant.Message.JobPublishNotification, Constant.TextFormatter.FormatValue(transformName), jobName, eventType)
            };
            Job job = GetEntity <Job>(MediaEntity.TransformJob, jobName, transformName);

            if (job != null)
            {
                switch (eventType)
                {
                case Constant.Media.Job.EventType.Errored:
                    string jobError = null;
                    foreach (JobOutput jobOutput in job.Outputs)
                    {
                        if (!string.IsNullOrEmpty(jobError))
                        {
                            jobError = string.Concat(jobError, Constant.Message.NewLine);
                        }
                        jobError = string.Concat(jobError, jobOutput.Error.Message);
                    }
                    publishNotification.StatusMessage = string.Concat(publishNotification.StatusMessage, Constant.Message.NewLine, jobError);
                    break;

                case Constant.Media.Job.EventType.Finished:
                    string settingKey        = Constant.AppSettingKey.MediaPlayerDemoUrl;
                    string mediaPlayerUrl    = AppSetting.GetValue(settingKey);
                    string outputPublishData = job.CorrelationData[Constant.Media.Job.CorrelationData.OutputPublish].ToString();
                    MediaJobOutputPublish jobOutputPublish = JsonConvert.DeserializeObject <MediaJobOutputPublish>(outputPublishData);
                    foreach (JobOutputAsset jobOutput in job.Outputs)
                    {
                        Asset             outputAsset = GetEntity <Asset>(MediaEntity.Asset, jobOutput.AssetName);
                        StorageBlobClient blobClient  = new StorageBlobClient(this.MediaAccount, outputAsset.StorageAccountName);
                        if (blobClient.ContainsFile(outputAsset.Container, null, null, Constant.Media.Stream.ManifestExtension))
                        {
                            StreamingLocator streamingLocator = GetStreamingLocator(jobOutput.AssetName, jobOutput.AssetName, jobOutputPublish.StreamingPolicyName, jobOutputPublish.ContentProtection);
                            string           mediaStreamUrl   = GetStreamingUrl(streamingLocator, null);
                            mediaStreamUrl = string.Format(mediaPlayerUrl, mediaStreamUrl);
                            publishNotification.StatusMessage = string.Concat(publishNotification.StatusMessage, Constant.Message.NewLine, mediaStreamUrl);
                        }
                    }
                    SetJobInputAssetArchive(job.Input, jobOutputPublish.InputAssetStorageTier);
                    break;
                }
            }
            return(publishNotification);
        }
Exemple #22
0
        private static async Task <StreamingLocator> CreateAssetAndLocatorAsync(IAzureMediaServicesClient client, string resourceGroup, string accountName, string assetName, string streamingLocatorName)
        {
            // Create an Asset for the LiveOutput to use
            Console.WriteLine($"Creating an asset named {assetName}");
            Console.WriteLine();
            Asset asset = await client.Assets.CreateOrUpdateAsync(resourceGroup, accountName, assetName, new Asset());

            // Create the StreamingLocator
            Console.WriteLine($"Creating a streaming locator named {streamingLocatorName}");
            Console.WriteLine();

            StreamingLocator locator = new StreamingLocator(assetName: asset.Name, streamingPolicyName: PredefinedStreamingPolicy.ClearStreamingOnly);

            return(await client.StreamingLocators.CreateAsync(resourceGroup, accountName, streamingLocatorName, locator));
        }
Exemple #23
0
        /// <summary>
        /// Takes input filename and creates, starts, and monitors processing job
        /// When job completes, video is stored in Azure Table Storage
        /// </summary>
        /// <param name="client">The Media Services client.</param>
        /// <param name="fileName">The name of the file to process with Azure Media Services</param>
        /// <returns></returns>
        // <ProcessVideo>
        public async Task ProcessVideo(IAzureMediaServicesClient client, string fileName)
        {
            await GetOrCreateTransformAsync(client, _config.ResourceGroup, _config.AccountName, AdaptiveStreamingTransformName);

            // 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().Substring(0, 13);
            string jobName         = "job-" + uniqueness;
            string locatorName     = "locator-" + uniqueness;
            string outputAssetName = "output-" + uniqueness;
            string inputAssetName  = "input-" + uniqueness;

            // Create a new input Asset and upload the specified local video file into it.
            await CreateInputAssetAsync(client, _config.ResourceGroup, _config.AccountName, inputAssetName, fileName);

            // Use the name of the created input asset to create the job input.
            JobInput jobInput = new JobInputAsset(assetName: inputAssetName);

            // 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, jobName, jobInput, outputAssetName);

            // 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)
            {
                StreamingLocator locator = CreateStreamingLocator(client, _config.ResourceGroup, _config.AccountName, outputAsset.Name, locatorName);

                IList <string> urls = GetStreamingURLs(client, _config.ResourceGroup, _config.AccountName, locator.Name);
                _log.LogInformation("Urls Created");
                foreach (var url in urls)
                {
                    _log.LogInformation(url);
                }
                // Get url of manifest file supported for Azure Media Player Playback
                var streamingUrl = urls.Where(a => a.EndsWith("manifest")).FirstOrDefault();

                await _storageHelpers.InsertTableRecord(fileName, streamingUrl);

                await _storageHelpers.DeleteBlobAsync(fileName);

                _log.LogInformation("Stream Processing Complete");
            }
        }
        public string[] GetStreamingUrls(string assetName)
        {
            List <string> streamingUrls = new List <string>();
            ListStreamingLocatorsResponse streamingLocatorList = _media.Assets.ListStreamingLocators(MediaAccount.ResourceGroupName, MediaAccount.Name, assetName);

            foreach (AssetStreamingLocator assetStreamingLocator in streamingLocatorList.StreamingLocators)
            {
                StreamingLocator streamingLocator = GetEntity <StreamingLocator>(MediaEntity.StreamingLocator, assetStreamingLocator.Name);
                string           streamingUrl     = GetStreamingUrl(streamingLocator, null);
                if (!string.IsNullOrEmpty(streamingUrl))
                {
                    streamingUrls.Add(streamingUrl);
                }
            }
            return(streamingUrls.ToArray());
        }
Exemple #25
0
        public static async Task <StreamingLocator> CreateClearLocator(ConfigWrapper config, string streamingLocatorName,
                                                                       IAzureMediaServicesClient client, Asset asset, Guid?streamingLocatorId)
        {
            var locator = new StreamingLocator(
                asset.Name,
                PredefinedStreamingPolicy.ClearStreamingOnly,
                defaultContentKeyPolicyName: null,
                contentKeys: null,
                streamingLocatorId: streamingLocatorId
                );

            locator = await client.StreamingLocators.CreateAsync(config.ResourceGroup, config.AccountName,
                                                                 streamingLocatorName, locator);

            return(locator);
        }
 internal static void ValidateLocator(StreamingLocator locator, string expectedName, string expectedAssetName, string expectedDefaultContentKeyPolicyName, string expectedStreamingPolicyName, string[] filters = null)
 {
     Assert.Equal(expectedAssetName, locator.AssetName);
     Assert.Equal(expectedName, locator.Name);
     Assert.Equal(expectedDefaultContentKeyPolicyName, locator.DefaultContentKeyPolicyName);
     Assert.NotEqual(Guid.Empty, locator.StreamingLocatorId);
     Assert.Equal(expectedStreamingPolicyName, locator.StreamingPolicyName);
     Assert.False(string.IsNullOrEmpty(locator.Id));
     if (filters != null)
     {
         foreach (string filter in filters)
         {
             Assert.True(locator.Filters.Contains(filter));
         }
     }
 }
        private async Task CreateStreamingLocatorAsync(Asset asset, string streamingLocatorName)
        {
            StreamingLocator locator = new StreamingLocator(
                assetName: asset.Name,
                streamingPolicyName: PredefinedStreamingPolicy.ClearStreamingOnly
                );

            await Client.StreamingLocators.CreateAsync(
                resourceGroupName : Config.ResourceGroup,
                accountName : Config.AccountName,
                streamingLocatorName : streamingLocatorName,
                parameters : locator
                );

            LoggerService.Info("Created the streaming locator", LoggerService.Start);
        }
        /// <summary>
        /// Publishes the Asset by creating an endpoint that can be used for streaming the
        /// video content.
        /// </summary>
        /// <param name="assetName">The name of the asset to publish.</param>
        /// <param name="streamingPolicyName">The name of the streaming policy to apply to the locator.</param>
        /// <returns>A task that represents the asynchronous operation.</returns>
        public async Task PublishAsset(string assetName, string streamingPolicyName)
        {
            Guid   streamingLocatorId   = Guid.NewGuid();
            string streamingLocatorName = "streaminglocator-" + streamingLocatorId.ToString();

            try
            {
                var asset = await this.GetAssetAsync(assetName).ConfigureAwait(false);

                var streamingPolicy = await this.Client.StreamingPolicies.GetAsync(
                    this.Options.ResourceGroup,
                    this.Options.AccountName,
                    streamingPolicyName)
                                      .ConfigureAwait(false);

                var streamingLocator = new StreamingLocator()
                {
                    AssetName                   = assetName,
                    StreamingPolicyName         = streamingPolicyName,
                    AlternativeMediaId          = streamingLocatorId.ToString(),
                    DefaultContentKeyPolicyName = null,
                    StartTime                   = null,
                    EndTime            = null,
                    StreamingLocatorId = streamingLocatorId,
                };

                streamingLocator.Validate();

                await this.Client.StreamingLocators.CreateAsync(
                    this.Options.ResourceGroup,
                    this.Options.AccountName,
                    streamingLocatorName,
                    streamingLocator).ConfigureAwait(false);
            }
            catch (ApiErrorException e)
            {
                this.Log.LogError("API error {Code} coccurred: {Message}", e.Body.Error.Code, e.Body.Error.Message);
            }
            catch (Exception e)
            {
                this.Log.LogError("An exception occurred: {Message}", e.Message);
            }

            this.Log.LogInformation("Created '{LocatorName}' with Id '{Id}'", streamingLocatorName, streamingLocatorId);
        }
        private static StreamingLocator CreateStreamingLocator(IAzureMediaServicesClient client,
                                                               string resourceGroup,
                                                               string accountName,
                                                               string assetName,
                                                               string locatorName)
        {
            StreamingLocator locator =
                client.StreamingLocators.Create(resourceGroup,
                                                accountName,
                                                locatorName,
                                                new StreamingLocator()
            {
                AssetName           = assetName,
                StreamingPolicyName = PredefinedClearStreamingOnly,
            });

            return(locator);
        }
Exemple #30
0
        private static string[] GetThumbnailUrls(MediaClient mediaClient, StreamingLocator locator)
        {
            List <string>     thumbnailUrls    = new List <string>();
            Asset             asset            = mediaClient.GetEntity <Asset>(MediaEntity.Asset, locator.AssetName);
            MediaAsset        mediaAsset       = new MediaAsset(mediaClient, asset);
            StorageBlobClient blobClient       = new StorageBlobClient(mediaClient.MediaAccount, asset.StorageAccountName);
            StringComparison  stringComparison = StringComparison.OrdinalIgnoreCase;

            foreach (MediaFile assetFile in mediaAsset.Files)
            {
                if (assetFile.Name.StartsWith(Constant.Media.Thumbnail.FileNamePrefix, stringComparison))
                {
                    string thumbnailUrl = blobClient.GetDownloadUrl(asset.Container, assetFile.Name, false);
                    thumbnailUrls.Add(thumbnailUrl);
                }
            }
            return(thumbnailUrls.ToArray());
        }