Пример #1
0
        public ActionResult ViewPortal()
        {
            var model = new List <VideoModel>();
            // var dal = new Repository();
            //var videos = db.Videos.OrderByDescending(p => p.Id).ToList().Take(2);
            //var videos = dal.GetVideosList(); for sql db
            WebClient wc        = new WebClient();
            var       videojson = wc.DownloadString(Server.MapPath("~/Content/Video.json"));
            var       videos    = JsonConvert.DeserializeObject <List <Video> >(videojson);

            foreach (var video in videos)
            {
                var viewModel = new VideoModel();
                viewModel.Id             = video.Id;
                viewModel.EncodedAssetId = video.EncodedAssetId;
                viewModel.IsEncrypted    = video.IsEncrypted;
                viewModel.LocatorUri     = video.LocatorUri;
                viewModel.Status         = AzureMediaAsset.GetEncodingJobStatus(video.EncodingJobId);
                viewModel.FileType       = video.filetype;
                viewModel.FileName       = video.AssetFileName ?? null; //if assetfilename is null it will take null
                // If encrypted content, then get token to play
                if (video.IsEncrypted)
                {
                    IAsset asset = GetAssetById(video.EncodedAssetId);
                    viewModel.Token = AzureMediaAsset.GetTestToken(asset.Id, asset);
                }

                model.Add(viewModel);
            }

            return(View(model));
        }
Пример #2
0
        private ActionResult CommitAllChunks(CloudFile model)
        {
            model.IsUploadCompleted = true;
            bool errorInOperation = false;

            try
            {
                var blockList = Enumerable.Range(1, (int)model.BlockCount).ToList <int>().ConvertAll(rangeElement => Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format(CultureInfo.InvariantCulture, "{0:D4}", rangeElement))));
                model.BlockBlob.PutBlockList(blockList);
                var    duration        = DateTime.Now - model.StartTime;
                float  fileSizeInKb    = model.Size / 1024;
                string fileSizeMessage = fileSizeInKb > 1024 ? string.Concat((fileSizeInKb / 1024).ToString(CultureInfo.CurrentCulture), " MB") : string.Concat(fileSizeInKb.ToString(CultureInfo.CurrentCulture), " KB");
                model.UploadStatusMessage = string.Format(CultureInfo.CurrentCulture, "File of size {0} took {1} seconds to upload.", fileSizeMessage, duration.TotalSeconds);

                IAsset mediaServiceAsset = CreateMediaAsset(model);
                model.AssetId = mediaServiceAsset.Id;
                //IAsset file = RunIndexingJob(mediaServiceAsset.Id);
                //// Download the job output asset.
                //var restult=DownloadAsset(file, HttpContext.Server.MapPath("~/Media/Output"));
            }
            catch (StorageException e)
            {
                model.UploadStatusMessage = "Failed to upload file. Exception - " + e.Message;
                errorInOperation          = true;
            }
            return(Json(new
            {
                error = errorInOperation,
                isLastBlock = model.IsUploadCompleted,
                message = model.UploadStatusMessage,
                assetId = model.AssetId,
            }));
        }
Пример #3
0
        internal static IAsset GetAssetById(string assetId)
        {
            IAsset theAsset = (from a in context.Assets
                               where a.Id == assetId
                               select a).FirstOrDefault();

            return(theAsset);
        }
Пример #4
0
        private IAsset CreateMediaAsset(CloudFile model)
        {
            CloudStorageAccount storageAccount     = CloudStorageAccount.Parse(mediaServiceStorageConnectionString);
            CloudBlobClient     cloudBlobClient    = storageAccount.CreateCloudBlobClient();
            CloudBlobContainer  mediaBlobContainer = cloudBlobClient.GetContainerReference(mediaServiceStorageContainerReference);

            mediaBlobContainer.CreateIfNotExists();

            // Create a new asset.
            IAsset        asset              = context.Assets.Create("UploadedVideo-" + Guid.NewGuid().ToString().ToLower(), AssetCreationOptions.None);
            IAccessPolicy writePolicy        = context.AccessPolicies.Create("writePolicy", TimeSpan.FromMinutes(120), AccessPermissions.Write);
            ILocator      destinationLocator = context.Locators.CreateLocator(LocatorType.Sas, asset, writePolicy);

            // Get the asset container URI and copy blobs from mediaContainer to assetContainer.
            Uri                uploadUri          = new Uri(destinationLocator.Path);
            string             assetContainerName = uploadUri.Segments[1];
            CloudBlobContainer assetContainer     = cloudBlobClient.GetContainerReference(assetContainerName);
            string             fileName           = HttpUtility.UrlDecode(Path.GetFileName(model.BlockBlob.Uri.AbsoluteUri));

            var sourceCloudBlob = mediaBlobContainer.GetBlockBlobReference(fileName);

            sourceCloudBlob.FetchAttributes();

            if (sourceCloudBlob.Properties.Length > 0)
            {
                IAssetFile assetFile       = asset.AssetFiles.Create(fileName);
                var        destinationBlob = assetContainer.GetBlockBlobReference(fileName);

                destinationBlob.DeleteIfExists();
                // not present anymore
                //  destinationBlob.StartCopyFromBlob(sourceCloudBlob);
                destinationBlob.FetchAttributes();
                if (sourceCloudBlob.Properties.Length != destinationBlob.Properties.Length)
                {
                    model.UploadStatusMessage += "Failed to copy as Media Asset!";
                }
            }
            destinationLocator.Delete();
            writePolicy.Delete();
            sourceCloudBlob.Delete();  //delete temp blob

            // Refresh the asset.
            asset = context.Assets.Where(a => a.Id == asset.Id).FirstOrDefault();

            var ismAssetFiles = asset.AssetFiles.FirstOrDefault();

            ismAssetFiles.IsPrimary = true;
            ismAssetFiles.Update();

            model.UploadStatusMessage += " Media file uploaded successfully by id: " + asset.Id;
            model.AssetId              = asset.Id;

            return(asset);
        }
Пример #5
0
        public List <string> DeleteAssetInMediaService(string assetId, string jobname)
        {
            // var dal = new Repository();
            //var videos = db.Videos.OrderByDescending(p => p.Id).ToList().Take(2);
            //List<string> videos = dal.GetVideosList().Select(p => p.AssetId).ToList();
            //List<string>list=dal.GetVideosList().Select(p => p.EncodedAssetId).ToList();
            //videos.AddRange(list);
            List <IAsset> assets = context.Assets.ToList();

            //List<IAsset> assets = new List<IAsset>();
            //List<string> selectedlist = assets.Select(p=>p.Id).Except(videos).ToList();

            List <string> selectedlist1 = assets.Select(p => p.Id).ToList();

            List <string> notfoundlist = new List <string>();

            IAsset asset = assets.Where(p => p.Id == assetId).FirstOrDefault();

            string iteratevariable = "";

            try
            {
                if (null != assets)
                {
                    int i = 0;
                    foreach (var va in assets.Select(p => p.Id).ToList())
                    {
                        var locators = context.Locators.Where(l => l.AssetId == va);
                        foreach (var l in locators)
                        {
                            l.Delete();
                        }
                        assets[i].Delete();
                        i++;
                    }


                    return(new List <string>(new string[] { "Done" }));
                }
                return(notfoundlist);
            }
            catch (Exception ex)
            {
                if (ex.InnerException.Message.ToString().Contains("Asset's storage container cannot be found") || ex.InnerException.ToString().Contains("Asset's storage container cannot be found") || ex.Message.ToString().Contains("Asset's storage container cannot be found"))
                {
                    //selectedlist.Remove(iteratevariable);
                    notfoundlist.Add(iteratevariable);
                    DeleteAssetInMediaService(assetId, jobname);
                }

                return(new List <string>(new string[] { "Failed" + ex.Message + "\n" + ex.InnerException + "\n" }));
            }
        }
Пример #6
0
        // Create locator and get urls
        static public string PublishAssetGetURLs(IAsset asset)
        {
            // A locator expiry can be set to maximum 100 years, using 99 years below.
            TimeSpan      daysForWhichStreamingUrlIsActive = DateTime.Now.AddYears(99) - DateTime.Now;
            IAccessPolicy videoWatchPolicy   = context.AccessPolicies.Create("videoWatchPolicy", daysForWhichStreamingUrlIsActive, AccessPermissions.Read);
            ILocator      destinationLocator = context.Locators.CreateLocator(LocatorType.OnDemandOrigin, asset, videoWatchPolicy);

            // Get the asset container URI
            Uri uploadUri = new Uri(destinationLocator.Path);

            // Note: You need atleast 1 reserve streaming unit for dynamic packaging of encoded media. If you don't have that, you can't see video file playing
            return(uploadUri.ToString() + asset.Name + ".ism/manifest");
        }
Пример #7
0
        static public string GetStreamingOriginLocator(IAsset asset, string filename)
        {
            // Get a reference to the streaming manifest file from the collection of files in the asset.
            //var assetFile = asset.AssetFiles.Where(f => f.Name.ToLower().EndsWith(".ism")).FirstOrDefault();

            // A locator expiry can be set to maximum 100 years, using 99 years below.
            TimeSpan      daysForWhichStreamingUrlIsActive = DateTime.Now.AddYears(99) - DateTime.Now;
            IAccessPolicy policy = context.AccessPolicies.Create("Streaming policy", daysForWhichStreamingUrlIsActive, AccessPermissions.Read);

            // Create a locator to the streaming content on an origin.
            ILocator originLocator = context.Locators.CreateLocator(LocatorType.OnDemandOrigin, asset, policy, DateTime.UtcNow.AddMinutes(-5));

            // Create a URL to the manifest file.

            return(GetWithoutHttp(originLocator.Path + Path.GetFileNameWithoutExtension(filename) + ".ism/manifest"));
        }
Пример #8
0
        public string DownloadAsset()
        {
            IAsset asset = (IAsset)Session["indexingMediaAssets"];

            foreach (IAssetFile file in asset.AssetFiles)
            {
                file.Download(Server.MapPath("~/Media/Output/") + file.Name);
                if (file.Name.Substring(file.Name.Length - 4) == ".vtt")
                {
                    textParsed            = Parseresult("~/Media/Output/" + file.Name);
                    Session["link"]       = "Media/Output/" + file.Name;
                    Session["textParsed"] = textParsed;
                    break;
                }
            }
            return(textParsed);
        }
Пример #9
0
        static public IContentKey CreateEnvelopeTypeContentKey(IAsset asset)
        {
            // Create envelope encryption content key
            Guid keyId = Guid.NewGuid();

            byte[] contentKey = GetRandomBuffer(16);

            IContentKey key = context.ContentKeys.Create(
                keyId,
                contentKey,
                "ContentKey",
                ContentKeyType.EnvelopeEncryption);

            // Associate the key with the asset.
            asset.ContentKeys.Add(key);

            return(key);
        }
Пример #10
0
        public void ProcessPolicyAndEncryption(IAsset asset)
        {
            IContentKey key = CreateEnvelopeTypeContentKey(asset);

            if (useAESRestriction)
            {
                // AES restriction
                AddTokenRestrictedAuthorizationPolicy(key);
            }
            else
            {
                // No restriction
                AddOpenAuthorizationPolicy(key);
            }

            // Set asset delivery policy
            CreateAssetDeliveryPolicy(asset, key);
        }
Пример #11
0
        public ActionResult RunIndexingJob(string assetId)
        {
            // Create an asset and upload the input media file to storage.
            IAsset asset = GetAssetById(assetId);

            // Declare a new job.
            IJob job = context.Jobs.Create("My Indexing Job");

            // Get a reference to Azure Media Indexer 2 Preview.
            string MediaProcessorName = "Azure Media Indexer 2 Preview";

            var processor = GetLatestMediaProcessorByName(MediaProcessorName);

            // Read configuration from the specified file.


            string configuration = System.IO.File.ReadAllText(HttpContext.Server.MapPath("~/config.json"));
            // Create a task with the encoding details, using a string preset.
            ITask task = job.Tasks.AddNew("My Indexing Task",
                                          processor,
                                          configuration,
                                          TaskOptions.None);

            // Specify the input asset to be indexed.
            task.InputAssets.Add(asset);

            // Add an output asset to contain the results of the job.
            task.OutputAssets.AddNew("My Indexing Output Asset", AssetCreationOptions.None);
            // Launch the job.
            job.Submit();
            // Check job execution and wait for job to finish.
            //Task progressJobTask = job.GetExecutionProgressTask(CancellationToken.None);

            //progressJobTask.Wait();
            Session["indexingMediaAssets"] = job.OutputMediaAssets[0];
            //return job.OutputMediaAssets[0];
            return(Json(new
            {
                message = "Indexing Job Submitted",
                assetId = assetId,
                jobId = job.Id
            }));
        }
Пример #12
0
        static public void CreateAssetDeliveryPolicy(IAsset asset, IContentKey key)
        {
            Uri keyAcquisitionUri = key.GetKeyDeliveryUrl(ContentKeyDeliveryType.BaselineHttp);

            string envelopeEncryptionIV = Convert.ToBase64String(GetRandomBuffer(16));

            // The following policy configuration specifies: key url that will have KID=<Guid> appended to the envelope and
            // the Initialization Vector (IV) to use for the envelope encryption.
            Dictionary <AssetDeliveryPolicyConfigurationKey, string> assetDeliveryPolicyConfiguration =
                new Dictionary <AssetDeliveryPolicyConfigurationKey, string>
            {
                { AssetDeliveryPolicyConfigurationKey.EnvelopeKeyAcquisitionUrl, keyAcquisitionUri.ToString() }
            };

            IAssetDeliveryPolicy assetDeliveryPolicy =
                context.AssetDeliveryPolicies.Create(
                    "AssetDeliveryPolicy",
                    AssetDeliveryPolicyType.DynamicEnvelopeEncryption,
                    AssetDeliveryProtocol.SmoothStreaming | AssetDeliveryProtocol.HLS | AssetDeliveryProtocol.Dash,
                    assetDeliveryPolicyConfiguration);

            // Add AssetDelivery Policy to the asset
            asset.DeliveryPolicies.Add(assetDeliveryPolicy);
        }
Пример #13
0
        public ActionResult EncodeToAdaptiveBitrateMP4s(string assetId)
        {
            // Note: You need atleast 1 reserve streaming unit for dynamic packaging of encoded media. If you don't have that, you can't see video file playing.

            IAsset inputAsset             = GetAssetById(assetId);
            string token                  = string.Empty;
            string uploadFileOriginalName = string.Empty;
            string fileName               = string.Empty;

            ////// Without preset (say default preset), works very well
            //IJob job = context.Jobs.CreateWithSingleTask(MediaProcessorNames.AzureMediaEncoder,
            //    MediaEncoderTaskPresetStrings.H264AdaptiveBitrateMP4Set720p,
            //    inputAsset,
            //    "UploadedVideo-" + Guid.NewGuid().ToString().ToLower() + "-Adaptive-Bitrate-MP4",
            //    AssetCreationOptions.None);
            //job.Submit();
            //IAsset encodedOutputAsset = job.OutputMediaAssets[0];


            //// XML Preset
            IJob job = context.Jobs.Create(inputAsset.Name);

            if (inputAsset.AssetType.ToString() == "Video")
            {
                IMediaProcessor processor     = GetLatestMediaProcessorByName("Media Encoder Standard");
                string          configuration = System.IO.File.ReadAllText(HttpContext.Server.MapPath("~/MediaServicesCustomPreset.xml"));
                ITask           task          = job.Tasks.AddNew(inputAsset.Name + "- encoding task", processor, configuration, TaskOptions.None);
                task.InputAssets.Add(inputAsset);
                task.OutputAssets.AddNew(inputAsset.Name + "-Adaptive-Bitrate-MP4", AssetCreationOptions.None);
            }

            else if (true)
            {
                IMediaProcessor processor     = GetLatestMediaProcessorByName("Media Encoder Standard");
                string          configuration = System.IO.File.ReadAllText(HttpContext.Server.MapPath("~/MediaServicesCustomPreset.xml"));
                ITask           task          = job.Tasks.AddNew("Media Encoder Standard encoding task", processor, "Adaptive Streaming", TaskOptions.None);

                //ITask task = job.Tasks.AddNew("My encoding task", processor, configuration, TaskOptions.None);
                task.InputAssets.Add(inputAsset);
                task.OutputAssets.AddNew(inputAsset.Name + "-Adaptive-Bitrate-MP4", AssetCreationOptions.None);
            }
            job.Submit();

            //Task progressJobTask = job.GetExecutionProgressTask(CancellationToken.None);

            //progressJobTask.Wait();
            IAsset encodedAsset = job.OutputMediaAssets[0];

            // process policy & encryption
            ProcessPolicyAndEncryption(encodedAsset);

            // Get file name
            string fileSession = "CurrentFile";

            if (Session[fileSession] != null)
            {
                CloudFile model = (CloudFile)Session[fileSession];
                uploadFileOriginalName = model.OriginalName;
                fileName = model.FileName;
            }
            // Generate Streaming URL
            string smoothStreamingUri = GetStreamingOriginLocator(encodedAsset, fileName);

            // add jobid and output asset id in database
            var video = new Video();

            video.AssetId        = assetId;
            video.EncodingJobId  = job.Id;
            video.EncodedAssetId = encodedAsset.Id;
            video.LocatorUri     = smoothStreamingUri;
            video.IsEncrypted    = useAESRestriction;
            video.IndexedAssetId = ((IAsset)Session["indexingMediaAssets"]).Id;
            video.AssetFileName  = uploadFileOriginalName;
            video.text           = Session["textParsed"].ToString();
            var videoformatlist = new List <string> {
                ".mp4", ".avi", ".mkv", ".flv", ".wmv"
            };
            var audioformatlist = new List <string> {
                ".wav", ".mp3", ".aac"
            };
            var format = uploadFileOriginalName.Substring(uploadFileOriginalName.Length - 4);

            if (videoformatlist.Contains(format))
            {
                video.filetype = "video";
            }
            else if (audioformatlist.Contains(format))
            {
                video.filetype = "audio";
            }
            else
            {
                video.filetype = "other";
            }

            //  Repository dal = new Repository();
            //var result = dal.SaveVideo(video);
            SaveVideoListtoJson(video);
            if (useAESRestriction)
            {
                token = AzureMediaAsset.GetTestToken(encodedAsset.Id, encodedAsset);
            }

            // Remove session
            Session.Remove("CurrentFile");
            Session.Clear();
            // return success response
            return(Json(new
            {
                error = false,
                message = "Congratulations! Video is uploaded and pipelined for encoding, check console log for after encoding playback details.",
                assetId = assetId,
                jobId = job.Id,
                locator = smoothStreamingUri,
                encrypted = useAESRestriction,
                token = token
            }));
        }
Пример #14
0
        public IAsset CreateMediaAsset()
        {
            _sourceStorageAccount =
                new CloudStorageAccount(new StorageCredentials(_sourceStorageAccountName,
                                                               _sourceStorageAccountKey), true);

            _destinationStorageAccount =
                new CloudStorageAccount(new StorageCredentials(_sourceStorageAccountName,
                                                               _sourceStorageAccountKey), true);

            CloudBlobClient sourceCloudBlobClient =
                _sourceStorageAccount.CreateCloudBlobClient();
            CloudBlobContainer sourceContainer =
                sourceCloudBlobClient.GetContainerReference(_NameOfBlobContainerYouWantToCopy);


            CloudBlobClient destBlobStorage = _destinationStorageAccount.CreateCloudBlobClient();

            // Create a new asset.
            IAsset asset = context.Assets.Create("NewAsset_" + Guid.NewGuid(), AssetCreationOptions.None);

            IAccessPolicy writePolicy = context.AccessPolicies.Create("writePolicy",
                                                                      TimeSpan.FromHours(24), AccessPermissions.Write);

            ILocator destinationLocator =
                context.Locators.CreateLocator(LocatorType.Sas, asset, writePolicy);

            // Get the asset container URI and Blob copy from mediaContainer to assetContainer.
            CloudBlobContainer destAssetContainer =
                destBlobStorage.GetContainerReference((new Uri(destinationLocator.Path)).Segments[1]);

            if (destAssetContainer.CreateIfNotExists())
            {
                destAssetContainer.SetPermissions(new BlobContainerPermissions
                {
                    PublicAccess = BlobContainerPublicAccessType.Blob
                });
            }

            var blobList = sourceContainer.ListBlobs();

            foreach (CloudBlockBlob sourceBlob in blobList)
            {
                //var assetFile = asset.AssetFiles.Create((sourceBlob as ICloudBlob).Name);

                //ICloudBlob destinationBlob = destAssetContainer.GetBlockBlobReference(assetFile.Name);

                //CopyBlob(sourceBlob, destAssetContainer);

                //sourceBlob.FetchAttributes();
                //assetFile.ContentFileSize = (sourceBlob as ICloudBlob).Properties.Length;
                //assetFile.Update();
                //Console.WriteLine("File {0} is of {1} size", assetFile.Name, assetFile.ContentFileSize);
            }

            asset.Update();

            destinationLocator.Delete();
            writePolicy.Delete();

            // Set the primary asset file.
            // If, for example, we copied a set of Smooth Streaming files,
            // set the .ism file to be the primary file.
            // If we, for example, copied an .mp4, then the mp4 would be the primary file.
            var ismAssetFile = asset.AssetFiles.ToList().
                               Where(f => f.Name.EndsWith(".ism", StringComparison.OrdinalIgnoreCase)).ToArray().FirstOrDefault();

            // The following code assigns the first .ism file as the primary file in the asset.
            // An asset should have one .ism file.
            if (ismAssetFile != null)
            {
                ismAssetFile.IsPrimary = true;
                ismAssetFile.Update();
            }

            //CloudStorageAccount storageAccount = CloudStorageAccount.Parse(mediaServiceStorageConnectionString);
            //CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();
            //CloudBlobContainer mediaBlobContainer = cloudBlobClient.GetContainerReference(mediaServiceStorageContainerReference);

            //mediaBlobContainer.CreateIfNotExists();

            //// Create a new asset.
            //IAsset asset = context.Assets.Create("UploadedVideo-" + Guid.NewGuid().ToString().ToLower(), AssetCreationOptions.None);
            //IAccessPolicy writePolicy = context.AccessPolicies.Create("writePolicy", TimeSpan.FromMinutes(120), AccessPermissions.Write);
            //ILocator destinationLocator = context.Locators.CreateLocator(LocatorType.Sas, asset, writePolicy);

            //// Get the asset container URI and copy blobs from mediaContainer to assetContainer.
            //Uri uploadUri = new Uri(destinationLocator.Path);
            //string assetContainerName = uploadUri.Segments[1];
            //CloudBlobContainer assetContainer = cloudBlobClient.GetContainerReference(assetContainerName);
            //string fileName = HttpUtility.UrlDecode(Path.GetFileName("https://leadsstorageacc.blob.core.windows.net/sibot/SI_Operations%20%26%20Finance_NWS_Billable%20T%26E%2C%20October%2031%2C%202017.mp4"));

            //var sourceCloudBlob = mediaBlobContainer.GetBlockBlobReference(fileName);
            //sourceCloudBlob.FetchAttributes();

            //if (sourceCloudBlob.Properties.Length > 0)
            //{
            //    IAssetFile assetFile = asset.AssetFiles.Create(fileName);
            //    var destinationBlob = assetContainer.GetBlockBlobReference(fileName);

            //    destinationBlob.DeleteIfExists();
            //    destinationBlob.StartCopyFromBlob(sourceCloudBlob);
            //    destinationBlob.FetchAttributes();
            //    if (sourceCloudBlob.Properties.Length != destinationBlob.Properties.Length)
            //        model.UploadStatusMessage += "Failed to copy as Media Asset!";
            //}
            //destinationLocator.Delete();
            //writePolicy.Delete();
            //sourceCloudBlob.Delete();  //delete temp blob

            //// Refresh the asset.
            //asset = context.Assets.Where(a => a.Id == asset.Id).FirstOrDefault();

            //var ismAssetFiles = asset.AssetFiles.FirstOrDefault();
            //ismAssetFiles.IsPrimary = true;
            //ismAssetFiles.Update();

            //model.UploadStatusMessage += " Media file uploaded successfully by id: " + asset.Id;
            //model.AssetId = asset.Id;
            //IAsset file =RunIndexingJob(asset.Id);
            //// Download the job output asset.
            //DownloadAsset(file, HttpContext.Server.MapPath("~/Media/Output"));

            EncodeToAdaptiveBitrateMP4s(asset.Id);
            return(asset);
        }