예제 #1
0
        private TransformOutput GetTransformOutput(MediaTransformOutput transformOutput, Image thumbnailCodec)
        {
            Preset transformPreset = null;

            switch (transformOutput.PresetType)
            {
            case MediaTransformPreset.AdaptiveStreaming:
                EncoderNamedPreset presetName = EncoderNamedPreset.AdaptiveStreaming;
                if (!string.IsNullOrEmpty(transformOutput.PresetName))
                {
                    presetName = transformOutput.PresetName;
                }
                transformPreset = new BuiltInStandardEncoderPreset(presetName);
                break;

            case MediaTransformPreset.ContentAwareEncoding:
                transformPreset = new BuiltInStandardEncoderPreset(EncoderNamedPreset.ContentAwareEncodingExperimental);
                break;

            case MediaTransformPreset.ThumbnailImages:
            case MediaTransformPreset.ThumbnailSprite:
                transformPreset = GetThumbnailGeneration(thumbnailCodec);
                break;

            case MediaTransformPreset.VideoAnalyzer:
                transformPreset = new VideoAnalyzerPreset()
                {
                    InsightsToExtract = InsightsType.VideoInsightsOnly
                };
                break;

            case MediaTransformPreset.AudioAnalyzer:
                transformPreset = new AudioAnalyzerPreset();
                break;

            case MediaTransformPreset.FaceDetector:
                transformPreset = new FaceDetectorPreset();
                break;
            }
            if (transformPreset == null)
            {
                return(null);
            }
            else
            {
                return(new TransformOutput(transformPreset)
                {
                    RelativePriority = transformOutput.RelativePriority,
                    OnError = transformOutput.OnError
                });
            }
        }
예제 #2
0
        private Preset GetAnalyzerPreset(bool audioOnly)
        {
            Preset analyzerPreset;

            if (audioOnly)
            {
                analyzerPreset = new AudioAnalyzerPreset();
            }
            else
            {
                analyzerPreset = new VideoAnalyzerPreset();
            }
            return(analyzerPreset);
        }
예제 #3
0
        public Transform CreateTransform(string transformName, string transformDescription, MediaTransformOutput[] transformOutputs, int?thumbnailSpriteColumns)
        {
            Transform transform   = null;
            bool      defaultName = string.IsNullOrEmpty(transformName);
            List <TransformOutput> transformOutputPresets = new List <TransformOutput>();

            foreach (MediaTransformOutput transformOutput in transformOutputs)
            {
                TransformOutput transformOutputPreset;
                switch (transformOutput.TransformPreset)
                {
                case MediaTransformPreset.AdaptiveStreaming:
                    transformName = GetTransformName(defaultName, transformName, transformOutput);
                    BuiltInStandardEncoderPreset standardEncoderPreset = new BuiltInStandardEncoderPreset(EncoderNamedPreset.AdaptiveStreaming);
                    transformOutputPreset = GetTransformOutput(standardEncoderPreset, transformOutput);
                    transformOutputPresets.Add(transformOutputPreset);
                    break;

                case MediaTransformPreset.ThumbnailImages:
                    transformName = GetTransformName(defaultName, transformName, transformOutput);
                    StandardEncoderPreset thumbnailPreset = GetThumbnailPreset(thumbnailSpriteColumns);
                    transformOutputPreset = GetTransformOutput(thumbnailPreset, transformOutput);
                    transformOutputPresets.Add(transformOutputPreset);
                    break;

                case MediaTransformPreset.VideoAnalyzer:
                    transformName = GetTransformName(defaultName, transformName, transformOutput);
                    VideoAnalyzerPreset videoAnalyzerPreset = (VideoAnalyzerPreset)GetAnalyzerPreset(false);
                    transformOutputPreset = GetTransformOutput(videoAnalyzerPreset, transformOutput);
                    transformOutputPresets.Add(transformOutputPreset);
                    break;

                case MediaTransformPreset.AudioAnalyzer:
                    transformName = GetTransformName(defaultName, transformName, transformOutput);
                    AudioAnalyzerPreset audioAnalyzerPreset = (AudioAnalyzerPreset)GetAnalyzerPreset(true);
                    transformOutputPreset = GetTransformOutput(audioAnalyzerPreset, transformOutput);
                    transformOutputPresets.Add(transformOutputPreset);
                    break;
                }
            }
            if (transformOutputPresets.Count > 0)
            {
                transform = _media.Transforms.CreateOrUpdate(MediaAccount.ResourceGroupName, MediaAccount.Name, transformName, transformOutputPresets.ToArray(), transformDescription);
            }
            return(transform);
        }
예제 #4
0
        private void ListBoxOutputs_SelectedIndexChanged(object sender, EventArgs e)
        {
            TransformOutput output = _transform.Outputs.Skip(listBoxOutputs.SelectedIndex).Take(1).FirstOrDefault();

            DGOutputs.Rows.Clear();

            DGOutputs.Rows.Add("Preset type", output.Preset.GetType().ToString());

            string presetJson;

            if (output.Preset.GetType() == typeof(BuiltInStandardEncoderPreset))
            {
                BuiltInStandardEncoderPreset pmes = (BuiltInStandardEncoderPreset)output.Preset;
                presetJson = JsonConvert.SerializeObject(pmes, Newtonsoft.Json.Formatting.Indented);
            }
            else if (output.Preset.GetType() == typeof(AudioAnalyzerPreset))
            {
                AudioAnalyzerPreset pmes = (AudioAnalyzerPreset)output.Preset;
                presetJson = JsonConvert.SerializeObject(pmes, Newtonsoft.Json.Formatting.Indented);
            }
            else if (output.Preset.GetType() == typeof(StandardEncoderPreset))
            {
                StandardEncoderPreset pmes = (StandardEncoderPreset)output.Preset;
                presetJson = JsonConvert.SerializeObject(pmes, Newtonsoft.Json.Formatting.Indented);
            }
            else if (output.Preset.GetType() == typeof(VideoAnalyzerPreset))
            {
                VideoAnalyzerPreset pmes = (VideoAnalyzerPreset)output.Preset;
                presetJson = JsonConvert.SerializeObject(pmes, Newtonsoft.Json.Formatting.Indented);
            }
            else if (output.Preset.GetType() == typeof(FaceDetectorPreset))
            {
                FaceDetectorPreset pmes = (FaceDetectorPreset)output.Preset;
                presetJson = JsonConvert.SerializeObject(pmes, Newtonsoft.Json.Formatting.Indented);
            }
            else
            {
                presetJson = JsonConvert.SerializeObject(output.Preset, Newtonsoft.Json.Formatting.Indented);
            }
            textBoxPresetJson.Text = presetJson;
            DGOutputs.Rows.Add("Relative Priority", output.RelativePriority);
        }
예제 #5
0
        internal static void ValidateTransform(Transform transform, string expectedTransformName, string expectedTransformDescription, TransformOutput[] expectedOutputs)
        {
            Assert.Equal(expectedTransformDescription, transform.Description);
            Assert.Equal(expectedTransformName, transform.Name);
            Assert.Equal(expectedOutputs.Length, transform.Outputs.Count);

            for (int i = 0; i < expectedOutputs.Length; i++)
            {
                Type expectedType = expectedOutputs[i].Preset.GetType();
                Assert.Equal(expectedType, transform.Outputs[i].Preset.GetType());

                if (typeof(BuiltInStandardEncoderPreset) == expectedType)
                {
                    BuiltInStandardEncoderPreset expected = (BuiltInStandardEncoderPreset)expectedOutputs[i].Preset;
                    BuiltInStandardEncoderPreset actual   = (BuiltInStandardEncoderPreset)transform.Outputs[i].Preset;

                    Assert.Equal(expected.PresetName, actual.PresetName);
                }
                else if (typeof(VideoAnalyzerPreset) == expectedType)
                {
                    VideoAnalyzerPreset expected = (VideoAnalyzerPreset)expectedOutputs[i].Preset;
                    VideoAnalyzerPreset actual   = (VideoAnalyzerPreset)transform.Outputs[i].Preset;

                    Assert.Equal(expected.InsightsToExtract, actual.InsightsToExtract);
                    Assert.Equal(expected.AudioLanguage, actual.AudioLanguage);
                }
                else if (typeof(AudioAnalyzerPreset) == expectedType)
                {
                    AudioAnalyzerPreset expected = (AudioAnalyzerPreset)expectedOutputs[i].Preset;
                    AudioAnalyzerPreset actual   = (AudioAnalyzerPreset)transform.Outputs[i].Preset;

                    Assert.Equal(expected.AudioLanguage, actual.AudioLanguage);
                }
                else
                {
                    throw new InvalidOperationException($"Unexpected type {expectedType.Name}");
                }
            }
        }
        private void listBoxOutputs_SelectedIndexChanged(object sender, EventArgs e)
        {
            TransformOutput output = _transform.Outputs.Skip(listBoxOutputs.SelectedIndex).Take(1).FirstOrDefault();

            DGOutputs.Rows.Clear();

            DGOutputs.Rows.Add("Preset type", output.Preset.GetType().ToString());

            if (output.Preset.GetType() == typeof(BuiltInStandardEncoderPreset))
            {
                BuiltInStandardEncoderPreset pmes = (BuiltInStandardEncoderPreset)output.Preset;
                DGOutputs.Rows.Add("Preset name", pmes.PresetName);
            }
            else if (output.Preset.GetType() == typeof(AudioAnalyzerPreset))
            {
                AudioAnalyzerPreset pmes = (AudioAnalyzerPreset)output.Preset;
                DGOutputs.Rows.Add("Audio language", pmes.AudioLanguage);
            }
            else if (output.Preset.GetType() == typeof(StandardEncoderPreset))
            {
                StandardEncoderPreset pmes = (StandardEncoderPreset)output.Preset;
                // DGOutputs.Rows.Add("Audio language", pmes.);
            }
            else if (output.Preset.GetType() == typeof(VideoAnalyzerPreset))
            {
                VideoAnalyzerPreset pmes = (VideoAnalyzerPreset)output.Preset;
                DGOutputs.Rows.Add("Audio language", pmes.AudioLanguage);
                DGOutputs.Rows.Add("Insights To Extract", pmes.InsightsToExtract);
            }
            else if (output.Preset.GetType() == typeof(FaceDetectorPreset))
            {
                FaceDetectorPreset pmes = (FaceDetectorPreset)output.Preset;
                DGOutputs.Rows.Add("Resolution", pmes.Resolution.HasValue ? pmes.Resolution.Value.ToString() : string.Empty);
            }

            DGOutputs.Rows.Add("Relative Priority", output.RelativePriority);
        }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation($"AMS v3 Function - CreateTransform was triggered!");

            string  requestBody = new StreamReader(req.Body).ReadToEnd();
            dynamic data        = JsonConvert.DeserializeObject(requestBody);

            if (data.transformName == null)
            {
                return(new BadRequestObjectResult("Please pass transformName in the input object"));
            }
            string transformName = data.transformName;

            if (data.mode == null)
            {
                return(new BadRequestObjectResult("Please pass mode in the input object"));
            }
            string description = null;

            if (data.description != null)
            {
                description = data.description;
            }

            string mode = data.mode;

            if (mode != "simple" && mode != "advanced")
            {
                return(new BadRequestObjectResult("Please pass valid mode in the input object"));
            }
            //
            // Simple Mode
            //
            if (mode == "simple" && data.preset == null)
            {
                return(new BadRequestObjectResult("Please pass preset in the input object"));
            }
            string presetName = data.preset;

            if (presetName == "CustomPreset" && data.customPresetJson == null)
            {
                return(new BadRequestObjectResult("Please pass customPresetJson in the input object"));
            }
            //
            // Advanced Mode
            //
            if (mode == "advanced" && data.transformOutputs == null)
            {
                return(new BadRequestObjectResult("Please pass transformOutputs in the input object"));
            }

            MediaServicesConfigWrapper amsconfig = new MediaServicesConfigWrapper();
            string transformId = null;

            JsonConverter[] jsonReaders =
            {
                new MediaServicesHelperJsonReader(),
                new MediaServicesHelperTimeSpanJsonConverter()
            };

            try
            {
                IAzureMediaServicesClient client = MediaServicesHelper.CreateMediaServicesClientAsync(amsconfig);

                // 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 transform = client.Transforms.Get(amsconfig.ResourceGroup, amsconfig.AccountName, transformName);
                if (transform == null)
                {
                    TransformOutput[]      outputs          = null;
                    List <TransformOutput> transformOutputs = new List <TransformOutput>();
                    if (mode == "simple")
                    {
                        Preset preset        = null;
                        string audioLanguage = null;
                        if (data.audioLanguage != null)
                        {
                            audioLanguage = data.audioLanguage;
                        }
                        if (presetName == "VideoAnalyzer")
                        {
                            bool insightEnabled = false;
                            if (data.insightsToExtract != null && InsightTypeList.ContainsKey(data.insightsToExtract))
                            {
                                insightEnabled = true;
                            }
                            preset = new VideoAnalyzerPreset(audioLanguage, insightEnabled ? InsightTypeList[data.insightsToExtract] : null);
                        }
                        else if (presetName == "AudioAnalyzer")
                        {
                            preset = new AudioAnalyzerPreset(audioLanguage);
                        }
                        else if (presetName == "CustomPreset")
                        {
                            preset = JsonConvert.DeserializeObject <StandardEncoderPreset>(data.customPresetJson.ToString(), jsonReaders);
                        }
                        else
                        {
                            if (!EncoderNamedPresetList.ContainsKey(presetName))
                            {
                                return(new BadRequestObjectResult("Preset not found"));
                            }
                            preset = new BuiltInStandardEncoderPreset(EncoderNamedPresetList[presetName]);
                        }

                        OnErrorType onError = OnErrorType.StopProcessingJob;
                        string      temp    = data.onError;
                        if (!string.IsNullOrEmpty(temp) && OnErrorTypeList.ContainsKey(temp))
                        {
                            onError = OnErrorTypeList[temp];
                        }

                        Priority relativePriority = Priority.Normal;
                        temp = data.relativePriority;
                        if (!string.IsNullOrEmpty(temp) && PriorityList.ContainsKey(temp))
                        {
                            relativePriority = PriorityList[temp];
                        }

                        transformOutputs.Add(new TransformOutput(preset, onError, relativePriority));
                        outputs = transformOutputs.ToArray();
                    }
                    else if (mode == "advanced")
                    {
                        List <TransformOutput> transformOutputList = JsonConvert.DeserializeObject <List <TransformOutput> >(data.transformOutputs.ToString(), jsonReaders);
                        outputs = transformOutputList.ToArray();
                    }
                    else
                    {
                        return(new BadRequestObjectResult("Invalid mode found"));
                    }

                    // Create Transform
                    transform = client.Transforms.CreateOrUpdate(amsconfig.ResourceGroup, amsconfig.AccountName, transformName, outputs);
                }
                transformId = transform.Id;
            }
            catch (ApiErrorException e)
            {
                log.LogError($"ERROR: AMS API call failed with error code: {e.Body.Error.Code} and message: {e.Body.Error.Message}");
                return(new BadRequestObjectResult("AMS API call error: " + e.Message + "\nError Code: " + e.Body.Error.Code + "\nMessage: " + e.Body.Error.Message));
            }
            catch (Exception e)
            {
                log.LogError($"ERROR: Exception with message: {e.Message}");
                return(new BadRequestObjectResult("Error: " + e.Message));
            }

            return((ActionResult) new OkObjectResult(new
            {
                transformName = transformName,
                transformId = transformId
            }));
        }
        /// <summary>
        /// Run the sample async.
        /// </summary>
        /// <param name="config">The param is of type ConfigWrapper. This class reads values from local configuration file.</param>
        /// <returns></returns>
        private static async Task RunAsync(ConfigWrapper config)
        {
            IAzureMediaServicesClient client;

            try
            {
                client = await CreateMediaServicesClientAsync(config);
            }
            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 outputAssetName = $"output-{uniqueness}";
            string inputAssetName  = $"input-{uniqueness}";

            // Create an analyzer preset with audio insights.
            Preset preset = new VideoAnalyzerPreset(audioLanguage: "en-US", insightsToExtract: InsightsType.AudioInsightsOnly);

            // Ensure that you have the desired encoding Transform. This is really a one time setup operation.
            // Once it is created, we won't delete it.
            Transform audioAnalyzerTransform = await GetOrCreateTransformAsync(client, config.ResourceGroup, config.AccountName, AudioAnalyzerTransformName, preset);

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

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

            EventProcessorHost eventProcessorHost = null;

            try
            {
                // First we will try to process Job events through Event Hub in real-time. If this fails for any reason,
                // we will fall-back on polling Job status instead.

                // Please refer README for Event Hub and storage settings.
                string storageConnectionString = string.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}",
                                                               config.StorageAccountName, config.StorageAccountKey);

                // Create a new host to process events from an Event Hub.
                Console.WriteLine("Creating a new host to process events from an Event Hub...");
                eventProcessorHost = new EventProcessorHost(config.EventHubName,
                                                            PartitionReceiver.DefaultConsumerGroupName, config.EventHubConnectionString,
                                                            storageConnectionString, config.StorageContainerName);

                // Create an AutoResetEvent to wait for the job to finish and pass it to EventProcessor so that it can be set when a final state event is received.
                AutoResetEvent jobWaitingEvent = new AutoResetEvent(false);

                // Registers the Event Processor Host and starts receiving messages. Pass in jobWaitingEvent so it can be called back.
                await eventProcessorHost.RegisterEventProcessorFactoryAsync(new MediaServicesEventProcessorFactory(jobName, jobWaitingEvent),
                                                                            EventProcessorOptions.DefaultOptions);

                // Create a Task list, adding a job waiting task and a timer task. Other tasks can be added too.
                IList <Task> tasks = new List <Task>();

                // Add a task to wait for the job to finish. The AutoResetEvent will be set when a final state is received by EventProcessor.
                Task jobTask = Task.Run(() =>
                                        jobWaitingEvent.WaitOne());
                tasks.Add(jobTask);

                // 30 minutes timeout.
                var tokenSource = new CancellationTokenSource();
                var timeout     = Task.Delay(30 * 60 * 1000, tokenSource.Token);
                tasks.Add(timeout);

                // Wait for tasks.
                if (await Task.WhenAny(tasks) == jobTask)
                {
                    // Job finished. Cancel the timer.
                    tokenSource.Cancel();
                    // Get the latest status of the job.
                    job = await client.Jobs.GetAsync(config.ResourceGroup, config.AccountName, AudioAnalyzerTransformName, jobName);
                }
                else
                {
                    // Timeout happened, Something might be wrong with job events. Fall-back on polling instead.
                    jobWaitingEvent.Set();
                    throw new Exception("Timeout happened.");
                }
            }
            catch (Exception)
            {
                Console.WriteLine("Warning: Failed to connect to Event Hub, please refer README for Event Hub and storage settings.");

                // 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.
                Console.WriteLine("Polling job status...");
                job = await WaitForJobToFinishAsync(client, config.ResourceGroup, config.AccountName, AudioAnalyzerTransformName, jobName);
            }
            finally
            {
                if (eventProcessorHost != null)
                {
                    Console.WriteLine("Job final state received, unregistering event processor...");

                    // Disposes of the Event Processor Host.
                    await eventProcessorHost.UnregisterEventProcessorAsync();

                    Console.WriteLine();
                }
            }

            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);
            }

            await CleanUpAsync(client, config.ResourceGroup, config.AccountName, AudioAnalyzerTransformName, inputAssetName, outputAssetName, jobName);
        }