/// <summary>
		/// Gets the draft data for the media entity with the given id.
		/// </summary>
		/// <param name="id">The id</param>
		/// <param name="type">The media type</param>
		/// <returns>The draft media data, null if the data wasn't found</returns>
		public virtual byte[] GetDraft(Guid id, MediaType type = MediaType.Media) {
			var path = GetPath(id, true, type);

			if (File.Exists(path))
				return File.ReadAllBytes(path);
			return null;
		}
Exemple #2
0
        public MPAInfo(MPAHeader hdr, UInt64 duration)
        {
            ai_ = new AudioInfo();
            ai_.bitRate = MPAHeaderParser.bitrate(hdr);
            ai_.bitsPerSample = 16;
            ai_.channels = (UInt16)(hdr.channelMode < 3 ? 2 : 1);
            ai_.sampleRate = MPAHeaderParser.samplingRate(hdr);
            ai_.layer = (UInt16)(4 - hdr.layer);
            ai_.vbr = false; //todo

            duration_ = duration;

            switch (hdr.version)
            {
                case 3:
                    {
                        mt_ = MediaType.MPEG10; break;
                    }
                case 2:
                    {
                        mt_ = MediaType.MPEG20; break;
                    }
                case 0:
                    {
                        mt_ = MediaType.MPEG25; break;
                    }
            }
        }
		/// <summary>
		/// Gets the data for the media entity with the given id.
		/// </summary>
		/// <param name="id">The id</param>
		/// <param name="type">The media type</param>
		/// <returns>The media data, null if the data wasn't found</returns>
		public byte[] Get(Guid id, MediaType type = MediaType.Media) {
			var path = GetPath(id, false, type) ;

			if (File.Exists(path))
				return File.ReadAllBytes(path) ;
			return null ;
		}
		/// <summary>
		/// Stores the given data for the media entity with the given id.
		/// </summary>
		/// <param name="id">The id</param>
		/// <param name="data">The media data</param>
		/// <param name="type">The media type</param>
		public void Put(Guid id, byte[] data, MediaType type = MediaType.Media) {
			var blob = GetBlock(type, id, false) ;

			using (var stream = new MemoryStream(data)) {
				blob.UploadFromStream(stream) ;
			}
		}
        private static string Serialize(MediaType mediaType, object value)
        {
            Stream stream = null;

            try
            {
                stream = new MemoryStream();

                new JsonFormat().Serialize(mediaType, value, stream);
                stream.Position = 0;

                using (StreamReader reader = new StreamReader(stream))
                {
                    stream = null;
                    return reader.ReadToEnd();
                }
            }
            finally
            {
                if (stream != null)
                {
                    stream.Dispose();
                }
            }
        }
        public void GivenARequest(string verb, string uri, byte[] content, MediaType contentType)
        {
            var destinationUri = new Uri("http://127.0.0.1:" + this.port + uri);

            WebRequest request = WebRequest.Create(destinationUri);
            request.Timeout = int.MaxValue;
            request.Method = verb;
            request.ContentLength = content != null ? content.Length : 0;

            if (request.ContentLength > 0)
            {
                request.ContentType = contentType.ToString();
                using (Stream requestStream = request.GetRequestStream())
                {
                    requestStream.Write(content, 0, content.Length);
                }
            }

            try
            {
                this.theResponse = request.GetResponse() as HttpWebResponse;
            }
            catch (WebException exception)
            {
                this.theResponse = exception.Response as HttpWebResponse;
            }
        }
		/// <summary>
		/// Represents an <see cref="AtomLink"/> instance initialized with the given <see cref="Uri"/>,
		/// title, <see cref="Relationship"/> and <see cref="Type"/>.
		/// </summary>
		/// <param name="href">The <see cref="Uri"/> of the link.</param>
		/// <param name="rel">The <see cref="Relationship"/> of the link.</param>
		/// <param name="type">The <see cref="Type"/> of the link.</param>
		/// <param name="title">The <see cref="Title"/> of the link.</param>
		public AtomLink(Uri href, Relationship rel, MediaType type, string title)
		{
			this.HRef = href;
			this.Title = title;
			this.Rel = rel;
			this.Type = type;
		}
 /// <summary>
 /// 
 /// </summary>
 /// <param name="channelName"></param>
 /// <param name="channelUri"></param>
 /// <param name="trackTitle"></param>
 public ChannelChangedEventArgs(MediaType mediaType, string channelName, Uri channelUri, string trackTitle)
 {
     _mediaType = mediaType;
     _trackName = trackTitle;
     _channelUri = channelUri;
     _channelName = channelName;
 }
        public MediaId GetWeixinMediaId(MediaType type, string path)
        {
            DataRow row = TrySelectRowWithKeys(type.ToString(), path);
            if (row == null)
            {
                SetCommands(AdapterCommand.Insert);
                MediaId mediaId = WeUtil.UploadFile(type, path);
                row = NewRow();
                row.BeginEdit();
                row["MediaType"] = type.ToString();
                row["MediaKey"] = path;
                SetMediaRow(row, mediaId);
                row.EndEdit();
                UpdateDatabase();

                return mediaId;
            }
            else
            {
                DateTime validDate = row["ValidDate"].Value<DateTime>();
                if (validDate > DateTime.Now)
                    return new MediaId(row["MediaId"].ToString());
                else
                {
                    SetCommands(AdapterCommand.Update);
                    MediaId mediaId = WeUtil.UploadFile(type, path);
                    row.BeginEdit();
                    SetMediaRow(row, mediaId);
                    row.EndEdit();
                    UpdateDatabase();

                    return mediaId;
                }
            }
        }
Exemple #10
0
        public MyMsrpSession(MySipStack sipStack, MsrpSession session, MediaType mediaType, String remoteUri)
            : base(sipStack)
        {
            this.mCallback = new MyMsrpCallback(this);
            base.mMediaType = mediaType;
            base.remotePartyUri = remoteUri;

            if (session == null)
            {
                base.outgoing = true;
            #if WINDOWS_PHONE
                mSession = org.doubango.WindowsPhone.BackgroundProcessController.Instance.rtMsrpSessionNew(sipStack.WrappedStack, mCallback);
            #else
                mSession = new MsrpSession(sipStack.WrappedStack, mCallback);
            #endif
            }
            else
            {
                base.outgoing = false;
                mSession = session;
                mSession.setCallback(mCallback);
            }

            // commons
            base.init();

            // SigComp
            base.SigCompId = sipStack.SigCompId;
            mSession.addHeader("Subject", "FIXME");
        }
Exemple #11
0
 public DownloadList SoftAdd(IEnumerable entries, MediaType mediaType)
 {
     var downloadList = new DownloadList(mediaType, OnDownloadStatusChange);
     foreach (var member in entries.Cast<YoutubeEntry>().Where(member => member.Uri != null)) downloadList.Entries.Add(member.Clone());
     if (downloadList.Entries.Count > 0) Entries.Add(downloadList);
     return downloadList;
 }
        /// <summary>
        /// Deletes all cached images related to the given id, both draft and published.
        /// </summary>
        /// <param name="id">The id</param>
        /// <param name="type">The media type</param>
        public virtual void Delete(Guid id, MediaType type = MediaType.Media)
        {
            var dir = new DirectoryInfo(type == MediaType.Media ? MediaPath : UploadPath);

            foreach (var file in dir.GetFiles(id.ToString() + "*"))
                file.Delete();
        }
Exemple #13
0
 public PersonalMessage(string personalmsg, MediaType mediatype, string[] currentmediacontent)
 {
     Message = personalmsg;
     mediaType = mediatype;
     content = currentmediacontent;
     Format = "{0}";
 }
Exemple #14
0
        protected void Initialize()
        {
            if (!isInitialized)
            {
                lock (syncRoot)
                {
                    if (!isInitialized)
                    {
                        string viewer = this.Request["view"];
                        if (!string.IsNullOrEmpty(viewer))
                        {
                            if (!Enum.TryParse<MediaType>(viewer, true, out view))
                            {
                                view = MediaType.Photo;
                            }
                        }

                        url = Request.QueryString[Constants.UrlIdentifier] as string;
                        string query = Query; // read once to initialize

                        isInitialized = true;
                    }
                }
            }
        }
 internal static WeMaterialPageData GetPageData(MediaType type, int offset, int count)
 {
     string url = WeUtil.GetUrl(WeMaterialConst.BATCH_GET_MATERIAL);
     WeMaterialQueryCondition request = new WeMaterialQueryCondition(type, offset, count);
     var result = WeUtil.PostDataToUri(url, request.WriteJson(), new WeMaterialPageData());
     return result;
 }
        /// <summary>
        /// Returns media file's data as stream, in case there is no appropriate MediaType for your media file pass MediaType.UNKNOWN
        /// </summary>
        /// <param name="id">id of media file</param>
        /// <param name="type">media type: jpeg, png, gif, mp3, mp4, wav</param>
        /// <returns>Media meta object</returns>
        /// <exception cref="BadRequestException">          in case HTTP response code is 400 - Bad request, the request was formatted improperly.</exception>
        /// <exception cref="UnauthorizedException">        in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.</exception>
        /// <exception cref="AccessForbiddenException">     in case HTTP response code is 403 - Forbidden, insufficient permissions.</exception>
        /// <exception cref="ResourceNotFoundException">    in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.</exception>
        /// <exception cref="InternalServerErrorException"> in case HTTP response code is 500 - Internal Server Error.</exception>
        /// <exception cref="CallfireApiException">         in case HTTP response code is something different from codes listed above.</exception>
        /// <exception cref="CallfireClientException">      in case error has occurred in client.</exception>
        public Stream GetData(long id, MediaType type)
        {
            string path = type == MediaType.UNKNOWN ? MEDIA_FILE_PATH.ReplaceFirst(ClientConstants.PLACEHOLDER, id.ToString()) :
                MEDIA_ITEM_ID_PATH.ReplaceFirst(ClientConstants.PLACEHOLDER, id.ToString()).ReplaceFirst(ClientConstants.PLACEHOLDER, ClientUtils.DescriptionAttr(type));

            return Client.GetFileData(path);
        }
 public MediaFileType(string name, string extension, string contentType, MediaType mediaType)
 {
     Name = name;
     Extension = extension;
     MediaType = mediaType;
     ContentType = contentType;
 }
Exemple #18
0
        public MyMsrpSession(MySipStack sipStack, MsrpSession session, MediaType mediaType, String remoteUri)
            : base(sipStack)
        {
            this.callback = new MyMsrpCallback(this);
            base.mediaType = mediaType;
            base.remotePartyUri = remoteUri;

            if (session == null)
            {
                base.outgoing = true;
                this.session = new MsrpSession(sipStack, this.callback);
            }
            else
            {
                base.outgoing = false;
                this.session = session;
                this.session.setCallback(this.callback);
            }

            // commons
            base.init();

            // SigComp
            base.SigCompId = sipStack.SigCompId;
        }
Exemple #19
0
 /// <summary>
 /// Create ATOM link from absolute or relative URI.
 /// </summary>
 /// <param name="href"></param>
 /// <param name="relationType"></param>
 /// <param name="mediaType"></param>
 /// <param name="title"></param>
 public AtomLink(Uri href, string relationType, MediaType mediaType, string title)
 {
     HRef = href;
       RelationType = relationType;
       MediaType = mediaType;
       Title = title;
 }
Exemple #20
0
        public MyAVSession(MySipStack sipStack, CallSession session, MediaType mediaType, InviteState callState)
            : base(sipStack)
        {
            this.session = (session == null) ? new CallSession(sipStack) : session;
            base.mediaType = mediaType;
            this.state = callState;

            // commons
            base.init();

            // SigComp
            base.SigCompId = sipStack.SigCompId;

            // 100rel
            this.session.set100rel(true); // will add "Supported: 100rel"

            /* 3GPP TS 24.173
            *
            * 5.1 IMS communication service identifier
            * URN used to define the ICSI for the IMS Multimedia Telephony Communication Service: urn:urn-7:3gpp-service.ims.icsi.mmtel.
            * The URN is registered at http://www.3gpp.com/Uniform-Resource-Name-URN-list.html.
            * Summary of the URN: This URN indicates that the device supports the IMS Multimedia Telephony Communication Service.
            *
            * Contact: <sip:[email protected];gr=urn:uuid:xxx;comp=sigcomp>;+g.3gpp.icsi-ref="urn%3Aurn-7%3A3gpp-service.ims.icsi.mmtel"
            * Accept-Contact: *;+g.3gpp.icsi-ref="urn%3Aurn-7%3A3gpp-service.ims.icsi.mmtel"
            * P-Preferred-Service: urn:urn-7:3gpp-service.ims.icsi.mmtel
            */
            this.session.addCaps("+g.3gpp.icsi-ref", "\"urn%3Aurn-7%3A3gpp-service.ims.icsi.mmtel\"");
            this.session.addHeader("Accept-Contact", "*;+g.3gpp.icsi-ref=\"urn%3Aurn-7%3A3gpp-service.ims.icsi.mmtel\"");
            this.session.addHeader("P-Preferred-Service", "urn:urn-7:3gpp-service.ims.icsi.mmtel");
        }
Exemple #21
0
 public MediaFileInfo(MediaType mediaType, ContainerType containerType, EncodingType encondingType, String path)
 {
     mMediaType = mediaType;
     mContainerType = containerType;
     mEncondingType = encondingType;
     mPath = path;
 }
 public void TheBaseTypeIsProcessedCorrectly()
 {
     MediaType content = new MediaType("application/xml");
     content.TopLevelMediaType.ShouldBe("application");
     content.Subtype.ShouldBe("xml");
     content.Quality.ShouldBe(1.0f);
 }
Exemple #23
0
 public static HttpEntity GetHttpEntity(InMemoryRequest postRequest, string data, MediaType MediaType)
 {
     var bytes = Encoding.UTF8.GetBytes(data);
     var httpEntity = new HttpEntity(postRequest.Entity.Headers, new MemoryStream(bytes)) { ContentLength = bytes.Length };
     httpEntity.ContentType = MediaType;
     return httpEntity;
 }
Exemple #24
0
 private void UpdateGenres(MediaType mediaType)
 {
     GenreFilter.Items.Clear();
     GenreFilter.Items.Add("All");
     GenreFilter.Items.AddRange(rentIt.GetAllGenres(mediaType));
     GenreFilter.SelectedIndex = 0;
 }
 public DownloadList(MediaType mediaType, ListDownloadStatusEventHandler onDownloadStatusChange = null, int poolSize = 3)
 {
     MediaType = mediaType;
     OnListDownloadStatusChange = onDownloadStatusChange;
     _ignoreDownloaded = false;
     _poolSize = poolSize;
 }
        public ICodecWithMediaTypeDefinition ForMediaType(MediaType mediaType)
        {
            var model = new MediaTypeModel { MediaType = mediaType };
            this.codecRegistration.MediaTypes.Add(model);

            return new CodecMediaTypeDefinition(this, model);
        }
        private string GetAcceptCharset(IHttpServerRequest httpRequest, MediaType acceptMediaType)
        {
            string firstAvailableEncoding = null;

            foreach (var requestedCharset in httpRequest.AcceptCharsets)
            {
                var encoding = EncodingCache.Default.GetEncoding(requestedCharset);
                firstAvailableEncoding = requestedCharset;

                if (encoding != null)
                    break;
            }

            if (string.IsNullOrEmpty(firstAvailableEncoding))
            {
                if (acceptMediaType == MediaType.JSON)
                {
                    firstAvailableEncoding = Configuration.Default.DefaultJSONCharset;
                }
                else if (acceptMediaType == MediaType.XML)
                {
                    firstAvailableEncoding = Configuration.Default.DefaultXMLCharset;
                }
                else
                {
                    throw new NotImplementedException("Accept media type is not supported.");
                }
            }

            return firstAvailableEncoding;
        }
 public CWindowCameraRequest(string owner, MediaType type)
 {
     InitializeComponent();
     requestOwner = owner;
     this.mType = type;
     lbltext.Text = String.Format("{0} request received from {1}\n",type, owner);
 }
        //These methods should only be used when an exact match was found
        private bool ParseMediaType(string input, out MediaType value)
        {
            input = input.CutToTag("title", true);
            input = input.CutToLast('(', CutDirection.Left, true);
            input = input.CutToFirst(')', CutDirection.Right, true);

            value = MediaType.Movie;
            return true;
            //if (!input.Contains(" "))
            //{
            //    value = ResultType.None;
            //    return true;
            //}

            //input = input.CutToLast(' ', CutDirection.Right, true);
            //switch (input.ToString())
            //{
            //    case "Video Game":
            //        value = ResultType.VideoGame;
            //        return true;
            //    case "Video":
            //        value = ResultType.Video;
            //        return true;
            //    case "TV":
            //        value = ResultType.TV;
            //        return true;
            //    case "TV series":
            //        value = ResultType.TVseries;
            //        return true;
            //    default:
            //        value = ResultType.None;
            //        return false;
            //}
        }
Exemple #30
0
 public object Convert(object value, Type targetType, object parameter, string language)
 {
     if (value != null)
     {
         MediaType mt = (MediaType)value;
         if (mt == MediaType.Audio)
         {
             return(new Uri("ms-appx:///Assets/Icons/Audio_white.png"));
         }
         else if (mt == MediaType.Video)
         {
             return(new Uri("ms-appx:///Assets/Icons/Video_white.png"));
         }
         else
         {
             return(null);
         }
     }
     else
     {
         return(null);
     }
 }
        public override int GetHashCode()
        {
            int hashCode = ControllerName.ToUpperInvariant().GetHashCode() ^ ActionName.ToUpperInvariant().GetHashCode();

            if (MediaType != null)
            {
                hashCode ^= MediaType.GetHashCode();
            }
            if (SampleDirection != null)
            {
                hashCode ^= SampleDirection.GetHashCode();
            }
            if (ParameterType != null)
            {
                hashCode ^= ParameterType.GetHashCode();
            }
            foreach (string parameterName in ParameterNames)
            {
                hashCode ^= parameterName.ToUpperInvariant().GetHashCode();
            }

            return(hashCode);
        }
        /// <summary>
        /// Appends image extension with given image identifier.
        /// </summary>
        /// <param name="fileName">A string containing the image identifier without image extension.</param>
        /// <returns></returns>
        public static string AddFileExtension(string fileName, MediaType mediaType)
        {
            string resultingString = null;

            switch (mediaType)
            {
            case MediaType.Image:
                string imageExtension = ConfigurationManager.AppSettings[NeeoConstants.ImageExtension].ToString();
                resultingString = fileName + "." + imageExtension;
                break;

            case MediaType.Audio:
                // add server audio file extension
                resultingString = null;
                break;

            case MediaType.Video:
                // add server audio file extension
                resultingString = null;
                break;
            }
            return(resultingString);
        }
        /// <summary>
        /// Initializes a new instance of the MediaPlayerViewModel class.
        /// </summary>
        /// <param name="chromecastService">The Chromecast service</param>
        /// <param name="subtitlesService"></param>
        /// <param name="cacheService">Caching service</param>
        /// <param name="mediaPath">Media path</param>
        /// <param name="mediaName">Media name</param>
        /// <param name="type">Media type</param>
        /// <param name="mediaStoppedAction">Media action to execute when media has been stopped</param>
        /// <param name="mediaEndedAction">Media action to execute when media has ended</param>
        /// <param name="playingProgress">Media playing progress</param>
        /// <param name="bufferProgress">The buffer progress</param>
        /// <param name="bandwidthRate">THe bandwidth rate</param>
        /// <param name="currentSubtitle">Subtitle</param>
        /// <param name="subtitles">Subtitles</param>
        public MediaPlayerViewModel(IChromecastService chromecastService, ISubtitlesService subtitlesService,
                                    ICacheService cacheService,
                                    string mediaPath,
                                    string mediaName, MediaType type, Action mediaStoppedAction,
                                    Action mediaEndedAction, IProgress <double> playingProgress = null, Progress <double> bufferProgress = null,
                                    Progress <BandwidthRate> bandwidthRate = null, Subtitle currentSubtitle = null,
                                    IEnumerable <Subtitle> subtitles       = null)
        {
            Logger.Info(
                $"Loading media : {mediaPath}.");
            RegisterCommands();
            _chromecastService = chromecastService;
            _chromecastService.StatusChanged += OnCastMediaStatusChanged;
            _subtitlesService   = subtitlesService;
            _cacheService       = cacheService;
            MediaPath           = mediaPath;
            MediaName           = mediaName;
            MediaType           = type;
            _mediaStoppedAction = mediaStoppedAction;
            _mediaEndedAction   = mediaEndedAction;
            BufferProgress      = bufferProgress;
            BandwidthRate       = bandwidthRate;
            ShowSubtitleButton  = MediaType != MediaType.Trailer;
            Volume           = 1d;
            _playingProgress = playingProgress;
            _subtitles       = new ObservableCollection <Subtitle>();
            if (subtitles != null)
            {
                _subtitles = new ObservableCollection <Subtitle>(subtitles);
            }

            if (currentSubtitle != null && currentSubtitle.LanguageName != LocalizationProviderHelper.GetLocalizedValue <string>("NoneLabel") &&
                !string.IsNullOrEmpty(currentSubtitle.FilePath))
            {
                CurrentSubtitle = currentSubtitle;
            }
        }
        public Hashes(IEnumerable <HashedFingerprint> fingerprints,
                      double durationInSeconds,
                      MediaType mediaType,
                      DateTime relativeTo,
                      IEnumerable <string> origins,
                      string streamId,
                      IDictionary <string, string> additionalProperties,
                      double timeOffset)
        {
            this.fingerprints = fingerprints.ToList();
            if (this.fingerprints.Any() && durationInSeconds <= 0)
            {
                throw new ArgumentException(nameof(durationInSeconds));
            }

            this.additionalProperties = new Dictionary <string, string>(additionalProperties);

            DurationInSeconds = durationInSeconds;
            RelativeTo        = relativeTo;
            Origins           = origins;
            StreamId          = streamId;
            MediaType         = mediaType;
            TimeOffset        = timeOffset;
        }
Exemple #35
0
        public void Media_Undelete()
        {
            //find existing content
            var media = new Media(GetExistingNodeId());
            //create new content based on the existing content in the same heirarchy
            var mt       = new MediaType(media.ContentType.Id);
            var parentId = media.ParentId;
            var newMedia = Media.MakeNew("NewMedia" + Guid.NewGuid().ToString("N"), mt, m_User, parentId);

            Assert.IsTrue(newMedia.Id > 0);

            //this will recycle the node
            newMedia.delete();
            Assert.IsTrue(newMedia.IsTrashed);
            Assert.IsTrue(newMedia.Path.Contains("," + (int)RecycleBin.RecycleBinType.Media + ","));

            //undelete the node (move it)
            newMedia.Move(parentId);
            Assert.IsFalse(newMedia.IsTrashed);
            Assert.IsFalse(newMedia.Path.Contains("," + (int)RecycleBin.RecycleBinType.Media + ","));

            //remove it completely
            RecycleAndDelete(newMedia);
        }
Exemple #36
0
        public bool Create(string path, MediaType mediaType, Dictionary <string, string> options, ulong sectors,
                           uint sectorSize)
        {
            if (sectorSize != 512)
            {
                ErrorMessage = "Unsupported sector size";
                return(false);
            }

            if (sectors > uint.MaxValue)
            {
                ErrorMessage = "Too many sectors";
                return(false);
            }

            if (!SupportedMediaTypes.Contains(mediaType))
            {
                ErrorMessage = $"Unsupport media format {mediaType}";
                return(false);
            }

            imageInfo = new ImageInfo {
                MediaType = mediaType, SectorSize = sectorSize, Sectors = sectors
            };

            try { writingStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); }
            catch (IOException e)
            {
                ErrorMessage = $"Could not create new image file, exception {e.Message}";
                return(false);
            }

            IsWriting    = true;
            ErrorMessage = null;
            return(true);
        }
        private static MediaType ReadMediaTypeArg(string[] args)
        {
            MediaType returnValue = MediaType.Mp4Low;

            try
            {
                var argInputString = args[MEDIA_TYPE_ARG_INDEX].ToLower();

                if (argInputString.StartsWith("h"))
                {
                    returnValue = MediaType.Mp4High;
                }
                else if (argInputString.Contains("mid"))
                {
                    returnValue = MediaType.Mp4Medium;
                }
                else if (argInputString.Contains("mp3"))
                {
                    returnValue = MediaType.Mp3;
                }
                else if (argInputString.Contains("s"))
                {
                    returnValue = MediaType.Slides;
                }
                else
                {
                    returnValue = MediaType.Mp4Low;
                }
            }
            catch (Exception)
            {
                returnValue = MediaType.Mp4Low;
            }

            return(returnValue);
        }
 /// <summary>
 /// Loads a local or remote movie file
 /// </summary>
 public bool Load(string filename, MediaType requestedType, bool playOnTextureImmediately, float seekPosition)
 {
     SetFilename(filename);
     return(videoPlayerLoad(mFilename, (int)requestedType, playOnTextureImmediately, seekPosition));
 }
Exemple #39
0
 public void SetUp()
 {
     Configuration = CodeGeneratorConfiguration.Create().MediaTypes;
     Parser        = new StructureParser(Configuration);
     ContentType   = new MediaType();
 }
 public Hashes(IEnumerable <HashedFingerprint> fingerprints, double durationInSeconds, MediaType mediaType, DateTime relativeTo) :
     this(fingerprints,
          durationInSeconds,
          mediaType,
          relativeTo,
          Enumerable.Empty <string>(),
          string.Empty,
          emptyDictionary,
          0)
 {
 }
Exemple #41
0
 internal static extern WebRTCErrorCode SetTransceiverDirection(IntPtr handle, uint sourceId, MediaType type, TransceiverDirection mode);
Exemple #42
0
 public void MyTestInitialize()
 {
     m_ExistingMediaType = GetExistingMediaType();
     m_NewRootMedia      = CreateNewUnderRoot(m_ExistingMediaType);
 }
Exemple #43
0
 public bool CanParse(MediaType format)
 {
     return(format != null && format.Matches(ContentType, Encoding));
 }
Exemple #44
0
        // TODO: Support extended
        public bool Create(string path, MediaType mediaType, Dictionary<string, string> options, ulong sectors,
                           uint sectorSize)
        {
            if(sectorSize != 512)
            {
                ErrorMessage = "Unsupported sector size";

                return false;
            }

            if(!SupportedMediaTypes.Contains(mediaType))
            {
                ErrorMessage = $"Unsupported media format {mediaType}";

                return false;
            }

            if((sectors * sectorSize) / DEFAULT_CLUSTER_SIZE > uint.MaxValue)
            {
                ErrorMessage = "Too many sectors for selected cluster size";

                return false;
            }

            _imageInfo = new ImageInfo
            {
                MediaType  = mediaType,
                SectorSize = sectorSize,
                Sectors    = sectors
            };

            try
            {
                _writingStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
            }
            catch(IOException e)
            {
                ErrorMessage = $"Could not create new image file, exception {e.Message}";

                return false;
            }

            uint batEntries = (uint)((sectors * sectorSize) / DEFAULT_CLUSTER_SIZE);

            if((sectors * sectorSize) % DEFAULT_CLUSTER_SIZE > 0)
                batEntries++;

            uint headerSectors = (uint)Marshal.SizeOf<Header>() + (batEntries * 4);

            if((uint)Marshal.SizeOf<Header>() + (batEntries % 4) > 0)
                headerSectors++;

            _pHdr = new Header
            {
                magic        = _magic,
                version      = PARALLELS_VERSION,
                sectors      = sectors,
                in_use       = PARALLELS_CLOSED,
                bat_entries  = batEntries,
                data_off     = headerSectors,
                cluster_size = DEFAULT_CLUSTER_SIZE / 512
            };

            _bat                    = new uint[batEntries];
            _currentWritingPosition = headerSectors * 512;

            IsWriting    = true;
            ErrorMessage = null;

            return true;
        }
Exemple #45
0
 public void SetItems(MediaType mediaType)
 {
     this.mediaType = mediaType;
     BindFieldTypeDropDown(FieldTypeDropDown);
 }
Exemple #46
0
 internal static extern WebRTCErrorCode GetMute(IntPtr handle, uint sourceId, MediaType type, out bool mute);
Exemple #47
0
 internal static extern WebRTCErrorCode GetPause(IntPtr handle, uint sourceId, MediaType type, out bool isPaused);
Exemple #48
0
 internal static extern WebRTCErrorCode SetPause(IntPtr handle, uint sourceId, MediaType type, bool pause);
        public override bool Equals(object obj)
        {
            HelpPageSampleKey otherKey = obj as HelpPageSampleKey;

            if (otherKey is null)
            {
                return(false);
            }

            return(string.Equals(ControllerName, otherKey.ControllerName, StringComparison.OrdinalIgnoreCase) & string.Equals(ActionName, otherKey.ActionName, StringComparison.OrdinalIgnoreCase) & (MediaType == otherKey.MediaType | (MediaType is object && MediaType.Equals(otherKey.MediaType))) & ParameterType == otherKey.ParameterType & SampleDirection.Equals(otherKey.SampleDirection) & ParameterNames.SetEquals(otherKey.ParameterNames));
        }
        private static IMedia CreateMedia(int nodeId)
        {
            MediaType mediaType = MediaTypeBuilder.CreateSimpleMediaType("image", "Image");

            return(MediaBuilder.CreateSimpleMedia(mediaType, "Test image", -1, nodeId));
        }
Exemple #51
0
 public IAsyncEnumerable <OneOf <IPagedData <MediaEdge>, IAniListError> > GetCharacterMediaEnumerable(int characterId, MediaType mediaType, int perPage)
 {
     return(AniListService.GetCharacterMedia(characterId, mediaType, perPage));
 }
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var clientBuilder = Client.NewBuilder();

            // Support self-signed certificates
            if (EnableUntrustedCertificates)
            {
                // Install the all-trusting trust manager
                var trustManager = customTrustManager ?? new CustomX509TrustManager();

                var sslContext = SSLContext.GetInstance("SSL");
                sslContext.Init(null, new ITrustManager[] { trustManager }, new Java.Security.SecureRandom());

                // Create an ssl socket factory with our all-trusting manager
                var sslSocketFactory = sslContext.SocketFactory;

                clientBuilder.SslSocketFactory(sslSocketFactory, trustManager);
            }

            if (Timeout != null)
            {
                var timeout = (long)Timeout.Value.TotalMilliseconds;
                clientBuilder.ConnectTimeout(timeout, TimeUnit.Milliseconds);
                clientBuilder.WriteTimeout(timeout, TimeUnit.Milliseconds);
                clientBuilder.ReadTimeout(timeout, TimeUnit.Milliseconds);
            }

            Client = clientBuilder.Build();

            //RegisterForProgress(request, this.HandleProgress);

            var java_uri = request.RequestUri.GetComponents(UriComponents.AbsoluteUri, UriFormat.UriEscaped);
            var url      = new Java.Net.URL(java_uri);

            var body = default(RequestBody);

            if (request.Content != null)
            {
                var bytes = await request.Content.ReadAsByteArrayAsync().ConfigureAwait(false);

                var contentType = "text/plain";
                if (request.Content.Headers.ContentType != null)
                {
                    contentType = String.Join(" ", request.Content.Headers.GetValues("Content-Type"));
                }
                body = RequestBody.Create(MediaType.Parse(contentType), bytes);
            }

            var requestBuilder = new Request.Builder()
                                 .Method(request.Method.Method.ToUpperInvariant(), body)
                                 .Url(url);

            if (DisableCaching)
            {
                requestBuilder.CacheControl(noCacheCacheControl);
            }

            var keyValuePairs = request.Headers
                                .Union(request.Content != null ?
                                       (IEnumerable <KeyValuePair <string, IEnumerable <string> > >)request.Content.Headers :
                                       Enumerable.Empty <KeyValuePair <string, IEnumerable <string> > >());

            // Add Cookie Header if there's any cookie for the domain in the cookie jar
            var stringBuilder = new StringBuilder();

            if (Client.CookieJar() != null)
            {
                var jar     = Client.CookieJar();
                var cookies = jar.LoadForRequest(HttpUrl.Get(url));
                foreach (var cookie in cookies)
                {
                    stringBuilder.Append(cookie.Name() + "=" + cookie.Value() + ";");
                }
            }

            foreach (var kvp in keyValuePairs)
            {
                if (kvp.Key == "Cookie")
                {
                    foreach (var val in kvp.Value)
                    {
                        stringBuilder.Append(val + ";");
                    }
                }
                else
                {
                    requestBuilder.AddHeader(kvp.Key, String.Join(getHeaderSeparator(kvp.Key), kvp.Value));
                }
            }

            if (stringBuilder.Length > 0)
            {
                requestBuilder.AddHeader("Cookie", stringBuilder.ToString().TrimEnd(';'));
            }

            cancellationToken.ThrowIfCancellationRequested();

            var rq   = requestBuilder.Build();
            var call = Client.NewCall(rq);

            // NB: Even closing a socket must be done off the UI thread. Cray!
            cancellationToken.Register(() => Task.Run(() => call.Cancel()));

            var resp = default(Response);

            try
            {
                resp = await call.EnqueueAsync().ConfigureAwait(false);

                var newReq = resp.Request();
                var newUri = newReq == null ? null : newReq.Url().Uri();
                request.RequestUri = new Uri(newUri.ToString());
                if (throwOnCaptiveNetwork && newUri != null)
                {
                    if (url.Host != newUri.Host)
                    {
                        throw new CaptiveNetworkException(new Uri(java_uri), new Uri(newUri.ToString()));
                    }
                }
            }
            catch (IOException ex)
            {
                if (ex.Message.ToLowerInvariant().Contains("canceled"))
                {
                    throw new System.OperationCanceledException();
                }

                // Calling HttpClient methods should throw .Net Exception when fail #5
                throw new HttpRequestException(ex.Message, ex);
            }

            /*catch (Java.Lang.LinkageError ex)
             * {
             *  throw new HttpRequestException(ex.Message, ex);
             * }*/

            var respBody = resp.Body();

            cancellationToken.ThrowIfCancellationRequested();

            var ret = new HttpResponseMessage((HttpStatusCode)resp.Code());

            ret.RequestMessage = request;
            ret.ReasonPhrase   = resp.Message();

            // ReasonPhrase is empty under HTTPS #8
            if (string.IsNullOrEmpty(ret.ReasonPhrase))
            {
                try
                {
                    ret.ReasonPhrase = ((ReasonPhrases)resp.Code()).ToString().Replace('_', ' ');
                }
#pragma warning disable 0168
                catch (Exception ex)
                {
                    ret.ReasonPhrase = "Unassigned";
                }
#pragma warning restore 0168
            }

            if (respBody != null)
            {
                var content = new ProgressStreamContent(request.RequestUri.AbsoluteUri, respBody.ByteStream(), CancellationToken.None);
                content.Progress = getAndRemoveCallbackFromRegister(request);
                ret.Content      = content;
            }
            else
            {
                ret.Content = new ByteArrayContent(new byte[0]);
            }

            var respHeaders = resp.Headers();
            foreach (var k in respHeaders.Names())
            {
                ret.Headers.TryAddWithoutValidation(k, respHeaders.Get(k));
                ret.Content.Headers.TryAddWithoutValidation(k, respHeaders.Get(k));
            }

            return(ret);
        }
Exemple #53
0
 public void UpdateAlbumForUser(int albumid, PurchaseStatus collectionStatus, MediaType mediaType, int rating)
 {
     Data.UpdateAlbumForUser(LoggedUserId, albumid, collectionStatus, mediaType, rating);
 }
Exemple #54
0
 public bool SuitableForResponse(MediaType component)
 {
     return(false);
 }
Exemple #55
0
        public bool Create(string path, MediaType mediaType, Dictionary <string, string> options, ulong sectors,
                           uint sectorSize)
        {
            if (sectorSize != 512)
            {
                ErrorMessage = "Unsupported sector size";
                return(false);
            }

            if (!SupportedMediaTypes.Contains(mediaType))
            {
                ErrorMessage = $"Unsupport media format {mediaType}";
                return(false);
            }

            // TODO: Correct this calculation
            if (sectors * sectorSize / 65536 > uint.MaxValue)
            {
                ErrorMessage = "Too many sectors for selected cluster size";
                return(false);
            }

            imageInfo = new ImageInfo {
                MediaType = mediaType, SectorSize = sectorSize, Sectors = sectors
            };

            try { writingStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); }
            catch (IOException e)
            {
                ErrorMessage = $"Could not create new image file, exception {e.Message}";
                return(false);
            }

            qHdr = new QCowHeader
            {
                magic           = QCOW_MAGIC,
                version         = QCOW_VERSION,
                size            = sectors * sectorSize,
                cluster_bits    = 12,
                l2_bits         = 9,
                l1_table_offset = (ulong)Marshal.SizeOf <QCowHeader>()
            };

            int shift = qHdr.cluster_bits + qHdr.l2_bits;

            clusterSize    = 1 << qHdr.cluster_bits;
            clusterSectors = 1 << (qHdr.cluster_bits - 9);
            l1Size         = (uint)((qHdr.size + (ulong)(1 << shift) - 1) >> shift);
            l2Size         = 1 << qHdr.l2_bits;

            l1Table = new ulong[l1Size];

            l1Mask = 0;
            int c = 0;

            l1Shift = qHdr.l2_bits + qHdr.cluster_bits;

            for (int i = 0; i < 64; i++)
            {
                l1Mask <<= 1;

                if (c >= 64 - l1Shift)
                {
                    continue;
                }

                l1Mask += 1;
                c++;
            }

            l2Mask = 0;
            for (int i = 0; i < qHdr.l2_bits; i++)
            {
                l2Mask = (l2Mask << 1) + 1;
            }

            l2Mask <<= qHdr.cluster_bits;

            sectorMask = 0;
            for (int i = 0; i < qHdr.cluster_bits; i++)
            {
                sectorMask = (sectorMask << 1) + 1;
            }

            byte[] empty = new byte[qHdr.l1_table_offset + l1Size * 8];
            writingStream.Write(empty, 0, empty.Length);

            IsWriting    = true;
            ErrorMessage = null;
            return(true);
        }
Exemple #56
0
 public bool CanParse(MediaType format)
 {
     return(false);
 }
Exemple #57
0
        public bool Create(string path, MediaType mediaType, Dictionary <string, string> options, ulong sectors,
                           uint sectorSize)
        {
            header = new Dc42Header();
            bool tags   = false;
            bool macosx = false;

            if (options != null && options.TryGetValue("macosx", out string tmpOption))
            {
                bool.TryParse(tmpOption, out macosx);
            }

            if (sectorSize != 512)
            {
                ErrorMessage = "Unsupported sector size";
                return(false);
            }

            switch (mediaType)
            {
            case MediaType.AppleFileWare:
                header.FmtByte = kSigmaFmtByteTwiggy;
                header.Format  = kSigmaFormatTwiggy;
                twiggy         = true;
                // TODO
                ErrorMessage = "Twiggy write support not yet implemented";
                return(false);

            case MediaType.AppleHD20:
                if (sectors != 39040)
                {
                    ErrorMessage = "Incorrect number of sectors for Apple HD20 image";
                    return(false);
                }

                header.FmtByte = kFmtNotStandard;
                header.Format  = kNotStandardFormat;
                tags           = true;
                break;

            case MediaType.AppleProfile:
                if (sectors != 9728 && sectors != 19456)
                {
                    ErrorMessage = "Incorrect number of sectors for Apple Profile image";
                    return(false);
                }

                header.FmtByte = kFmtNotStandard;
                header.Format  = kNotStandardFormat;
                tags           = true;
                break;

            case MediaType.AppleSonyDS:
                if (sectors != 1600)
                {
                    ErrorMessage = "Incorrect number of sectors for Apple MF2DD image";
                    return(false);
                }

                header.FmtByte = macosx ? kMacOSXFmtByte : kSonyFmtByte800K;
                header.Format  = kSonyFormat800K;
                tags           = true;
                break;

            case MediaType.AppleSonySS:
                if (sectors != 800)
                {
                    ErrorMessage = "Incorrect number of sectors for Apple MF1DD image";
                    return(false);
                }

                header.FmtByte = macosx ? kMacOSXFmtByte : kSonyFmtByte400K;
                header.Format  = kSonyFormat400K;
                tags           = true;
                break;

            case MediaType.AppleWidget:
                if (sectors != 39040)
                {
                    ErrorMessage = "Incorrect number of sectors for Apple Widget image";
                    return(false);
                }

                header.FmtByte = kFmtNotStandard;
                header.Format  = kNotStandardFormat;
                tags           = true;
                break;

            case MediaType.DOS_35_DS_DD_9:
                if (sectors != 1440)
                {
                    ErrorMessage = "Incorrect number of sectors for MF2DD image";
                    return(false);
                }

                header.FmtByte = macosx ? kMacOSXFmtByte : kSonyFmtByte720K;
                header.Format  = kSonyFormat720K;
                break;

            case MediaType.DOS_35_HD:
                if (sectors != 2880)
                {
                    ErrorMessage = "Incorrect number of sectors for MF2HD image";
                    return(false);
                }

                header.Format  = kSonyFmtByte1440K;
                header.FmtByte = macosx ? kMacOSXFmtByte : kSonyFmtByte1440K;
                break;

            case MediaType.DMF:
                if (sectors != 3360)
                {
                    ErrorMessage = "Incorrect number of sectors for DMF image";
                    return(false);
                }

                header.FmtByte = macosx ? kMacOSXFmtByte : kSonyFmtByte1680K;
                header.Format  = kSonyFormat1680K;
                break;

            default:
                ErrorMessage = $"Unsupport media format {mediaType}";
                return(false);
            }

            dataOffset      = 0x54;
            tagOffset       = header.TagSize != 0 ? 0x54 + header.DataSize : 0;
            header.DiskName = "-DiscImageChef converted image-";
            header.Valid    = 1;
            header.DataSize = (uint)(sectors * 512);
            if (tags)
            {
                header.TagSize = (uint)(sectors * 12);
            }

            imageInfo = new ImageInfo {
                MediaType = mediaType, SectorSize = sectorSize, Sectors = sectors
            };

            try { writingStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); }
            catch (IOException e)
            {
                ErrorMessage = $"Could not create new image file, exception {e.Message}";
                return(false);
            }

            IsWriting    = true;
            ErrorMessage = null;
            return(true);
        }
Exemple #58
0
        /// <summary>Dumps an ATA device</summary>
        void Ata()
        {
            if (_dumpRaw)
            {
                if (_force)
                {
                    ErrorMessage?.Invoke("Raw dumping not yet supported in ATA devices, continuing...");
                }
                else
                {
                    StoppingErrorMessage?.Invoke("Raw dumping not yet supported in ATA devices, aborting...");

                    return;
                }
            }

            const ushort ataProfile         = 0x0001;
            const uint   timeout            = 5;
            double       imageWriteDuration = 0;
            MediaType    mediaType          = MediaType.Unknown;

            UpdateStatus?.Invoke("Requesting ATA IDENTIFY DEVICE.");
            _dumpLog.WriteLine("Requesting ATA IDENTIFY DEVICE.");
            bool sense = _dev.AtaIdentify(out byte[] cmdBuf, out AtaErrorRegistersChs errorChs);

            if (sense)
            {
                _errorLog?.WriteLine("ATA IDENTIFY DEVICE", _dev.Error, _dev.LastError, errorChs);
            }
            else if (Identify.Decode(cmdBuf).HasValue)
            {
                Identify.IdentifyDevice?ataIdNullable = Identify.Decode(cmdBuf);

                if (ataIdNullable != null)
                {
                    Identify.IdentifyDevice ataId = ataIdNullable.Value;
                    byte[] ataIdentify            = cmdBuf;
                    cmdBuf = new byte[0];

                    DateTime start;
                    DateTime end;
                    double   totalDuration = 0;
                    double   currentSpeed  = 0;
                    double   maxSpeed      = double.MinValue;
                    double   minSpeed      = double.MaxValue;

                    // Initialize reader
                    UpdateStatus?.Invoke("Initializing reader.");
                    _dumpLog.WriteLine("Initializing reader.");
                    var ataReader = new Reader(_dev, timeout, ataIdentify, _errorLog);

                    // Fill reader blocks
                    ulong blocks = ataReader.GetDeviceBlocks();

                    // Check block sizes
                    if (ataReader.GetBlockSize())
                    {
                        _dumpLog.WriteLine("ERROR: Cannot get block size: {0}.", ataReader.ErrorMessage);
                        ErrorMessage(ataReader.ErrorMessage);

                        return;
                    }

                    uint blockSize          = ataReader.LogicalBlockSize;
                    uint physicalSectorSize = ataReader.PhysicalBlockSize;

                    if (ataReader.FindReadCommand())
                    {
                        _dumpLog.WriteLine("ERROR: Cannot find correct read command: {0}.", ataReader.ErrorMessage);
                        ErrorMessage(ataReader.ErrorMessage);

                        return;
                    }

                    // Check how many blocks to read, if error show and return
                    if (ataReader.GetBlocksToRead(_maximumReadable))
                    {
                        _dumpLog.WriteLine("ERROR: Cannot get blocks to read: {0}.", ataReader.ErrorMessage);
                        ErrorMessage(ataReader.ErrorMessage);

                        return;
                    }

                    uint   blocksToRead = ataReader.BlocksToRead;
                    ushort cylinders    = ataReader.Cylinders;
                    byte   heads        = ataReader.Heads;
                    byte   sectors      = ataReader.Sectors;

                    UpdateStatus?.Invoke($"Device reports {blocks} blocks ({blocks * blockSize} bytes).");

                    UpdateStatus?.
                    Invoke($"Device reports {cylinders} cylinders {heads} heads {sectors} sectors per track.");

                    UpdateStatus?.Invoke($"Device can read {blocksToRead} blocks at a time.");
                    UpdateStatus?.Invoke($"Device reports {blockSize} bytes per logical block.");
                    UpdateStatus?.Invoke($"Device reports {physicalSectorSize} bytes per physical block.");
                    _dumpLog.WriteLine("Device reports {0} blocks ({1} bytes).", blocks, blocks * blockSize);

                    _dumpLog.WriteLine("Device reports {0} cylinders {1} heads {2} sectors per track.", cylinders,
                                       heads, sectors);

                    _dumpLog.WriteLine("Device can read {0} blocks at a time.", blocksToRead);
                    _dumpLog.WriteLine("Device reports {0} bytes per logical block.", blockSize);
                    _dumpLog.WriteLine("Device reports {0} bytes per physical block.", physicalSectorSize);

                    bool removable = !_dev.IsCompactFlash &&
                                     ataId.GeneralConfiguration.HasFlag(Identify.GeneralConfigurationBit.Removable);

                    DumpHardwareType currentTry = null;
                    ExtentsULong     extents    = null;

                    ResumeSupport.Process(ataReader.IsLba, removable, blocks, _dev.Manufacturer, _dev.Model,
                                          _dev.Serial, _dev.PlatformId, ref _resume, ref currentTry, ref extents,
                                          _dev.FirmwareRevision, _private);

                    if (currentTry == null ||
                        extents == null)
                    {
                        StoppingErrorMessage?.Invoke("Could not process resume file, not continuing...");

                        return;
                    }

                    MhddLog mhddLog;
                    IbgLog  ibgLog;
                    double  duration;

                    bool ret = true;

                    if (_dev.IsUsb &&
                        _dev.UsbDescriptors != null &&
                        !_outputPlugin.SupportedMediaTags.Contains(MediaTagType.USB_Descriptors))
                    {
                        ret = false;
                        _dumpLog.WriteLine("Output format does not support USB descriptors.");
                        ErrorMessage("Output format does not support USB descriptors.");
                    }

                    if (_dev.IsPcmcia &&
                        _dev.Cis != null &&
                        !_outputPlugin.SupportedMediaTags.Contains(MediaTagType.PCMCIA_CIS))
                    {
                        ret = false;
                        _dumpLog.WriteLine("Output format does not support PCMCIA CIS descriptors.");
                        ErrorMessage("Output format does not support PCMCIA CIS descriptors.");
                    }

                    if (!_outputPlugin.SupportedMediaTags.Contains(MediaTagType.ATA_IDENTIFY))
                    {
                        ret = false;
                        _dumpLog.WriteLine("Output format does not support ATA IDENTIFY.");
                        ErrorMessage("Output format does not support ATA IDENTIFY.");
                    }

                    if (!ret)
                    {
                        _dumpLog.WriteLine("Several media tags not supported, {0}continuing...", _force ? "" : "not ");

                        if (_force)
                        {
                            ErrorMessage("Several media tags not supported, continuing...");
                        }
                        else
                        {
                            StoppingErrorMessage?.Invoke("Several media tags not supported, not continuing...");

                            return;
                        }
                    }

                    mediaType = MediaTypeFromDevice.GetFromAta(_dev.Manufacturer, _dev.Model, _dev.IsRemovable,
                                                               _dev.IsCompactFlash, _dev.IsPcmcia, blocks);

                    ret = _outputPlugin.Create(_outputPath, mediaType, _formatOptions, blocks, blockSize);

                    // Cannot create image
                    if (!ret)
                    {
                        _dumpLog.WriteLine("Error creating output image, not continuing.");
                        _dumpLog.WriteLine(_outputPlugin.ErrorMessage);

                        StoppingErrorMessage?.Invoke("Error creating output image, not continuing." +
                                                     Environment.NewLine + _outputPlugin.ErrorMessage);

                        return;
                    }

                    // Setting geometry
                    _outputPlugin.SetGeometry(cylinders, heads, sectors);

                    if (ataReader.IsLba)
                    {
                        UpdateStatus?.Invoke($"Reading {blocksToRead} sectors at a time.");

                        if (_skip < blocksToRead)
                        {
                            _skip = blocksToRead;
                        }

                        mhddLog = new MhddLog(_outputPrefix + ".mhddlog.bin", _dev, blocks, blockSize, blocksToRead,
                                              _private);

                        ibgLog = new IbgLog(_outputPrefix + ".ibg", ataProfile);

                        if (_resume.NextBlock > 0)
                        {
                            UpdateStatus?.Invoke($"Resuming from block {_resume.NextBlock}.");
                            _dumpLog.WriteLine("Resuming from block {0}.", _resume.NextBlock);
                        }

                        bool newTrim = false;

                        start = DateTime.UtcNow;
                        DateTime timeSpeedStart   = DateTime.UtcNow;
                        ulong    sectorSpeedStart = 0;
                        InitProgress?.Invoke();

                        for (ulong i = _resume.NextBlock; i < blocks; i += blocksToRead)
                        {
                            if (_aborted)
                            {
                                currentTry.Extents = ExtentsConverter.ToMetadata(extents);
                                UpdateStatus?.Invoke("Aborted!");
                                _dumpLog.WriteLine("Aborted!");

                                break;
                            }

                            if (blocks - i < blocksToRead)
                            {
                                blocksToRead = (byte)(blocks - i);
                            }

                            if (currentSpeed > maxSpeed &&
                                currentSpeed > 0)
                            {
                                maxSpeed = currentSpeed;
                            }

                            if (currentSpeed < minSpeed &&
                                currentSpeed > 0)
                            {
                                minSpeed = currentSpeed;
                            }

                            UpdateProgress?.Invoke($"Reading sector {i} of {blocks} ({currentSpeed:F3} MiB/sec.)",
                                                   (long)i, (long)blocks);

                            bool error = ataReader.ReadBlocks(out cmdBuf, i, blocksToRead, out duration);

                            if (!error)
                            {
                                mhddLog.Write(i, duration);
                                ibgLog.Write(i, currentSpeed * 1024);
                                DateTime writeStart = DateTime.Now;
                                _outputPlugin.WriteSectors(cmdBuf, i, blocksToRead);
                                imageWriteDuration += (DateTime.Now - writeStart).TotalSeconds;
                                extents.Add(i, blocksToRead, true);
                            }
                            else
                            {
                                if (i + _skip > blocks)
                                {
                                    _skip = (uint)(blocks - i);
                                }

                                for (ulong b = i; b < i + _skip; b++)
                                {
                                    _resume.BadBlocks.Add(b);
                                }

                                mhddLog.Write(i, duration < 500 ? 65535 : duration);

                                ibgLog.Write(i, 0);
                                DateTime writeStart = DateTime.Now;
                                _outputPlugin.WriteSectors(new byte[blockSize * _skip], i, _skip);
                                imageWriteDuration += (DateTime.Now - writeStart).TotalSeconds;
                                _dumpLog.WriteLine("Skipping {0} blocks from errored block {1}.", _skip, i);
                                i      += _skip - blocksToRead;
                                newTrim = true;
                            }

                            sectorSpeedStart += blocksToRead;
                            _resume.NextBlock = i + blocksToRead;

                            double elapsed = (DateTime.UtcNow - timeSpeedStart).TotalSeconds;

                            if (elapsed < 1)
                            {
                                continue;
                            }

                            currentSpeed     = (sectorSpeedStart * blockSize) / (1048576 * elapsed);
                            sectorSpeedStart = 0;
                            timeSpeedStart   = DateTime.UtcNow;
                        }

                        end = DateTime.Now;
                        EndProgress?.Invoke();
                        mhddLog.Close();

                        ibgLog.Close(_dev, blocks, blockSize, (end - start).TotalSeconds, currentSpeed * 1024,
                                     (blockSize * (double)(blocks + 1)) / 1024 / (totalDuration / 1000), _devicePath);

                        UpdateStatus?.Invoke($"Dump finished in {(end - start).TotalSeconds} seconds.");

                        UpdateStatus?.
                        Invoke($"Average dump speed {((double)blockSize * (double)(blocks + 1)) / 1024 / (totalDuration / 1000):F3} KiB/sec.");

                        UpdateStatus?.
                        Invoke($"Average write speed {((double)blockSize * (double)(blocks + 1)) / 1024 / imageWriteDuration:F3} KiB/sec.");

                        _dumpLog.WriteLine("Dump finished in {0} seconds.", (end - start).TotalSeconds);

                        _dumpLog.WriteLine("Average dump speed {0:F3} KiB/sec.",
                                           ((double)blockSize * (double)(blocks + 1)) / 1024 / (totalDuration / 1000));

                        _dumpLog.WriteLine("Average write speed {0:F3} KiB/sec.",
                                           ((double)blockSize * (double)(blocks + 1)) / 1024 / imageWriteDuration);

                        #region Trimming
                        if (_resume.BadBlocks.Count > 0 &&
                            !_aborted &&
                            _trim &&
                            newTrim)
                        {
                            start = DateTime.UtcNow;
                            UpdateStatus?.Invoke("Trimming skipped sectors");
                            _dumpLog.WriteLine("Trimming skipped sectors");

                            ulong[] tmpArray = _resume.BadBlocks.ToArray();
                            InitProgress?.Invoke();

                            foreach (ulong badSector in tmpArray)
                            {
                                if (_aborted)
                                {
                                    currentTry.Extents = ExtentsConverter.ToMetadata(extents);
                                    UpdateStatus?.Invoke("Aborted!");
                                    _dumpLog.WriteLine("Aborted!");

                                    break;
                                }

                                PulseProgress?.Invoke($"Trimming sector {badSector}");

                                bool error = ataReader.ReadBlock(out cmdBuf, badSector, out duration);

                                totalDuration += duration;

                                if (error)
                                {
                                    continue;
                                }

                                _resume.BadBlocks.Remove(badSector);
                                extents.Add(badSector);
                                _outputPlugin.WriteSector(cmdBuf, badSector);
                            }

                            EndProgress?.Invoke();
                            end = DateTime.UtcNow;
                            UpdateStatus?.Invoke($"Trimming finished in {(end - start).TotalSeconds} seconds.");
                            _dumpLog.WriteLine("Trimming finished in {0} seconds.", (end - start).TotalSeconds);
                        }
                        #endregion Trimming

                        #region Error handling
                        if (_resume.BadBlocks.Count > 0 &&
                            !_aborted &&
                            _retryPasses > 0)
                        {
                            int  pass    = 1;
                            bool forward = true;

                            InitProgress?.Invoke();
repeatRetryLba:
                            ulong[] tmpArray = _resume.BadBlocks.ToArray();

                            foreach (ulong badSector in tmpArray)
                            {
                                if (_aborted)
                                {
                                    currentTry.Extents = ExtentsConverter.ToMetadata(extents);
                                    UpdateStatus?.Invoke("Aborted!");
                                    _dumpLog.WriteLine("Aborted!");

                                    break;
                                }

                                PulseProgress?.Invoke(string.Format("Retrying sector {0}, pass {1}, {3}{2}", badSector,
                                                                    pass, forward ? "forward" : "reverse",
                                                                    _persistent ? "recovering partial data, " : ""));

                                bool error = ataReader.ReadBlock(out cmdBuf, badSector, out duration);

                                totalDuration += duration;

                                if (!error)
                                {
                                    _resume.BadBlocks.Remove(badSector);
                                    extents.Add(badSector);
                                    _outputPlugin.WriteSector(cmdBuf, badSector);
                                    UpdateStatus?.Invoke($"Correctly retried block {badSector} in pass {pass}.");
                                    _dumpLog.WriteLine("Correctly retried block {0} in pass {1}.", badSector, pass);
                                }
                                else if (_persistent)
                                {
                                    _outputPlugin.WriteSector(cmdBuf, badSector);
                                }
                            }

                            if (pass < _retryPasses &&
                                !_aborted &&
                                _resume.BadBlocks.Count > 0)
                            {
                                pass++;
                                forward = !forward;
                                _resume.BadBlocks.Sort();

                                if (!forward)
                                {
                                    _resume.BadBlocks.Reverse();
                                }

                                goto repeatRetryLba;
                            }

                            EndProgress?.Invoke();
                        }
                        #endregion Error handling LBA

                        currentTry.Extents = ExtentsConverter.ToMetadata(extents);
                    }
                    else
                    {
                        mhddLog = new MhddLog(_outputPrefix + ".mhddlog.bin", _dev, blocks, blockSize, blocksToRead,
                                              _private);

                        ibgLog = new IbgLog(_outputPrefix + ".ibg", ataProfile);

                        ulong currentBlock = 0;
                        blocks = (ulong)(cylinders * heads * sectors);
                        start  = DateTime.UtcNow;
                        DateTime timeSpeedStart   = DateTime.UtcNow;
                        ulong    sectorSpeedStart = 0;
                        InitProgress?.Invoke();

                        for (ushort cy = 0; cy < cylinders; cy++)
                        {
                            for (byte hd = 0; hd < heads; hd++)
                            {
                                for (byte sc = 1; sc < sectors; sc++)
                                {
                                    if (_aborted)
                                    {
                                        currentTry.Extents = ExtentsConverter.ToMetadata(extents);
                                        UpdateStatus?.Invoke("Aborted!");
                                        _dumpLog.WriteLine("Aborted!");

                                        break;
                                    }

                                    if (currentSpeed > maxSpeed &&
                                        currentSpeed > 0)
                                    {
                                        maxSpeed = currentSpeed;
                                    }

                                    if (currentSpeed < minSpeed &&
                                        currentSpeed > 0)
                                    {
                                        minSpeed = currentSpeed;
                                    }

                                    PulseProgress?.
                                    Invoke($"Reading cylinder {cy} head {hd} sector {sc} ({currentSpeed:F3} MiB/sec.)");

                                    bool error = ataReader.ReadChs(out cmdBuf, cy, hd, sc, out duration);

                                    totalDuration += duration;

                                    if (!error)
                                    {
                                        mhddLog.Write(currentBlock, duration);
                                        ibgLog.Write(currentBlock, currentSpeed * 1024);
                                        DateTime writeStart = DateTime.Now;

                                        _outputPlugin.WriteSector(cmdBuf,
                                                                  (ulong)((((cy * heads) + hd) * sectors) + (sc - 1)));

                                        imageWriteDuration += (DateTime.Now - writeStart).TotalSeconds;
                                        extents.Add(currentBlock);

                                        _dumpLog.WriteLine("Error reading cylinder {0} head {1} sector {2}.", cy, hd,
                                                           sc);
                                    }
                                    else
                                    {
                                        _resume.BadBlocks.Add(currentBlock);
                                        mhddLog.Write(currentBlock, duration < 500 ? 65535 : duration);

                                        ibgLog.Write(currentBlock, 0);
                                        DateTime writeStart = DateTime.Now;

                                        _outputPlugin.WriteSector(new byte[blockSize],
                                                                  (ulong)((((cy * heads) + hd) * sectors) + (sc - 1)));

                                        imageWriteDuration += (DateTime.Now - writeStart).TotalSeconds;
                                    }

                                    sectorSpeedStart++;
                                    currentBlock++;

                                    double elapsed = (DateTime.UtcNow - timeSpeedStart).TotalSeconds;

                                    if (elapsed < 1)
                                    {
                                        continue;
                                    }

                                    currentSpeed     = (sectorSpeedStart * blockSize) / (1048576 * elapsed);
                                    sectorSpeedStart = 0;
                                    timeSpeedStart   = DateTime.UtcNow;
                                }
                            }
                        }

                        end = DateTime.Now;
                        EndProgress?.Invoke();
                        mhddLog.Close();

                        ibgLog.Close(_dev, blocks, blockSize, (end - start).TotalSeconds, currentSpeed * 1024,
                                     (blockSize * (double)(blocks + 1)) / 1024 / (totalDuration / 1000), _devicePath);

                        UpdateStatus?.Invoke($"Dump finished in {(end - start).TotalSeconds} seconds.");

                        UpdateStatus?.
                        Invoke($"Average dump speed {((double)blockSize * (double)(blocks + 1)) / 1024 / (totalDuration / 1000):F3} KiB/sec.");

                        UpdateStatus?.
                        Invoke($"Average write speed {((double)blockSize * (double)(blocks + 1)) / 1024 / (imageWriteDuration / 1000):F3} KiB/sec.");

                        _dumpLog.WriteLine("Dump finished in {0} seconds.", (end - start).TotalSeconds);

                        _dumpLog.WriteLine("Average dump speed {0:F3} KiB/sec.",
                                           ((double)blockSize * (double)(blocks + 1)) / 1024 / (totalDuration / 1000));

                        _dumpLog.WriteLine("Average write speed {0:F3} KiB/sec.",
                                           ((double)blockSize * (double)(blocks + 1)) / 1024 /
                                           (imageWriteDuration / 1000));
                    }

                    foreach (ulong bad in _resume.BadBlocks)
                    {
                        _dumpLog.WriteLine("Sector {0} could not be read.", bad);
                    }

                    _outputPlugin.SetDumpHardware(_resume.Tries);

                    // TODO: Non-removable
                    var metadata = new CommonTypes.Structs.ImageInfo
                    {
                        Application        = "Aaru",
                        ApplicationVersion = Version.GetVersion()
                    };

                    if (!_outputPlugin.SetMetadata(metadata))
                    {
                        ErrorMessage?.Invoke("Error {0} setting metadata, continuing..." + Environment.NewLine +
                                             _outputPlugin.ErrorMessage);
                    }

                    if (_preSidecar != null)
                    {
                        _outputPlugin.SetCicmMetadata(_preSidecar);
                    }

                    _dumpLog.WriteLine("Closing output file.");
                    UpdateStatus?.Invoke("Closing output file.");
                    DateTime closeStart = DateTime.Now;
                    _outputPlugin.Close();
                    DateTime closeEnd = DateTime.Now;
                    UpdateStatus?.Invoke($"Closed in {(closeEnd - closeStart).TotalSeconds} seconds.");
                    _dumpLog.WriteLine("Closed in {0} seconds.", (closeEnd - closeStart).TotalSeconds);

                    if (_aborted)
                    {
                        _dumpLog.WriteLine("Aborted!");
                        UpdateStatus?.Invoke("Aborted!");

                        return;
                    }

                    double totalChkDuration = 0;

                    if (_metadata)
                    {
                        _dumpLog.WriteLine("Creating sidecar.");
                        UpdateStatus?.Invoke("Creating sidecar.");
                        var         filters     = new FiltersList();
                        IFilter     filter      = filters.GetFilter(_outputPath);
                        IMediaImage inputPlugin = ImageFormat.Detect(filter);

                        if (!inputPlugin.Open(filter))
                        {
                            StoppingErrorMessage?.Invoke("Could not open created image.");

                            return;
                        }

                        DateTime chkStart = DateTime.UtcNow;

                        _sidecarClass = new Sidecar(inputPlugin, _outputPath, filter.Id, _encoding);

                        _sidecarClass.InitProgressEvent    += InitProgress;
                        _sidecarClass.UpdateProgressEvent  += UpdateProgress;
                        _sidecarClass.EndProgressEvent     += EndProgress;
                        _sidecarClass.InitProgressEvent2   += InitProgress2;
                        _sidecarClass.UpdateProgressEvent2 += UpdateProgress2;
                        _sidecarClass.EndProgressEvent2    += EndProgress2;
                        _sidecarClass.UpdateStatusEvent    += UpdateStatus;
                        CICMMetadataType sidecar = _sidecarClass.Create();

                        if (_preSidecar != null)
                        {
                            _preSidecar.BlockMedia = sidecar.BlockMedia;
                            sidecar = _preSidecar;
                        }

                        if (_dev.IsUsb &&
                            _dev.UsbDescriptors != null)
                        {
                            _dumpLog.WriteLine("Reading USB descriptors.");
                            UpdateStatus?.Invoke("Reading USB descriptors.");
                            ret = _outputPlugin.WriteMediaTag(_dev.UsbDescriptors, MediaTagType.USB_Descriptors);

                            if (ret)
                            {
                                sidecar.BlockMedia[0].USB = new USBType
                                {
                                    ProductID   = _dev.UsbProductId,
                                    VendorID    = _dev.UsbVendorId,
                                    Descriptors = new DumpType
                                    {
                                        Image     = _outputPath,
                                        Size      = (ulong)_dev.UsbDescriptors.Length,
                                        Checksums = Checksum.GetChecksums(_dev.UsbDescriptors).ToArray()
                                    }
                                }
                            }
                            ;
                        }

                        if (_dev.IsPcmcia &&
                            _dev.Cis != null)
                        {
                            _dumpLog.WriteLine("Reading PCMCIA CIS.");
                            UpdateStatus?.Invoke("Reading PCMCIA CIS.");
                            ret = _outputPlugin.WriteMediaTag(_dev.Cis, MediaTagType.PCMCIA_CIS);

                            if (ret)
                            {
                                sidecar.BlockMedia[0].PCMCIA = new PCMCIAType
                                {
                                    CIS = new DumpType
                                    {
                                        Image     = _outputPath,
                                        Size      = (ulong)_dev.Cis.Length,
                                        Checksums = Checksum.GetChecksums(_dev.Cis).ToArray()
                                    }
                                }
                            }
                            ;

                            _dumpLog.WriteLine("Decoding PCMCIA CIS.");
                            UpdateStatus?.Invoke("Decoding PCMCIA CIS.");
                            Tuple[] tuples = CIS.GetTuples(_dev.Cis);

                            if (tuples != null)
                            {
                                foreach (Tuple tuple in tuples)
                                {
                                    switch (tuple.Code)
                                    {
                                    case TupleCodes.CISTPL_MANFID:
                                        ManufacturerIdentificationTuple manufacturerId =
                                            CIS.DecodeManufacturerIdentificationTuple(tuple);

                                        if (manufacturerId != null)
                                        {
                                            sidecar.BlockMedia[0].PCMCIA.ManufacturerCode =
                                                manufacturerId.ManufacturerID;

                                            sidecar.BlockMedia[0].PCMCIA.CardCode = manufacturerId.CardID;
                                            sidecar.BlockMedia[0].PCMCIA.ManufacturerCodeSpecified = true;
                                            sidecar.BlockMedia[0].PCMCIA.CardCodeSpecified         = true;
                                        }

                                        break;

                                    case TupleCodes.CISTPL_VERS_1:
                                        Level1VersionTuple version = CIS.DecodeLevel1VersionTuple(tuple);

                                        if (version != null)
                                        {
                                            sidecar.BlockMedia[0].PCMCIA.Manufacturer = version.Manufacturer;
                                            sidecar.BlockMedia[0].PCMCIA.ProductName  = version.Product;

                                            sidecar.BlockMedia[0].PCMCIA.Compliance =
                                                $"{version.MajorVersion}.{version.MinorVersion}";

                                            sidecar.BlockMedia[0].PCMCIA.AdditionalInformation =
                                                version.AdditionalInformation;
                                        }

                                        break;
                                    }
                                }
                            }
                        }

                        if (!_private)
                        {
                            DeviceReport.ClearIdentify(ataIdentify);
                        }

                        ret = _outputPlugin.WriteMediaTag(ataIdentify, MediaTagType.ATA_IDENTIFY);

                        if (ret)
                        {
                            sidecar.BlockMedia[0].ATA = new ATAType
                            {
                                Identify = new DumpType
                                {
                                    Image     = _outputPath,
                                    Size      = (ulong)cmdBuf.Length,
                                    Checksums = Checksum.GetChecksums(cmdBuf).ToArray()
                                }
                            }
                        }
                        ;

                        DateTime chkEnd = DateTime.UtcNow;

                        totalChkDuration = (chkEnd - chkStart).TotalMilliseconds;
                        UpdateStatus?.Invoke($"Sidecar created in {(chkEnd - chkStart).TotalSeconds} seconds.");

                        UpdateStatus?.
                        Invoke($"Average checksum speed {((double)blockSize * (double)(blocks + 1)) / 1024 / (totalChkDuration / 1000):F3} KiB/sec.");

                        _dumpLog.WriteLine("Sidecar created in {0} seconds.", (chkEnd - chkStart).TotalSeconds);

                        _dumpLog.WriteLine("Average checksum speed {0:F3} KiB/sec.",
                                           ((double)blockSize * (double)(blocks + 1)) / 1024 /
                                           (totalChkDuration / 1000));

                        List <(ulong start, string type)> filesystems = new List <(ulong start, string type)>();

                        if (sidecar.BlockMedia[0].FileSystemInformation != null)
                        {
                            filesystems.AddRange(from partition in sidecar.BlockMedia[0].FileSystemInformation
                                                 where partition.FileSystems != null
                                                 from fileSystem in partition.FileSystems
                                                 select(partition.StartSector, fileSystem.Type));
                        }

                        if (filesystems.Count > 0)
                        {
                            foreach (var filesystem in filesystems.Select(o => new
                            {
                                o.start,
                                o.type
                            }).Distinct())
                            {
                                UpdateStatus?.
                                Invoke($"Found filesystem {filesystem.type} at sector {filesystem.start}");

                                _dumpLog.WriteLine("Found filesystem {0} at sector {1}", filesystem.type,
                                                   filesystem.start);
                            }
                        }

                        (string type, string subType) = CommonTypes.Metadata.MediaType.MediaTypeToString(mediaType);

                        sidecar.BlockMedia[0].DiskType          = type;
                        sidecar.BlockMedia[0].DiskSubType       = subType;
                        sidecar.BlockMedia[0].Interface         = "ATA";
                        sidecar.BlockMedia[0].LogicalBlocks     = blocks;
                        sidecar.BlockMedia[0].PhysicalBlockSize = physicalSectorSize;
                        sidecar.BlockMedia[0].LogicalBlockSize  = blockSize;
                        sidecar.BlockMedia[0].Manufacturer      = _dev.Manufacturer;
                        sidecar.BlockMedia[0].Model             = _dev.Model;

                        if (!_private)
                        {
                            sidecar.BlockMedia[0].Serial = _dev.Serial;
                        }

                        sidecar.BlockMedia[0].Size = blocks * blockSize;

                        if (cylinders > 0 &&
                            heads > 0 &&
                            sectors > 0)
                        {
                            sidecar.BlockMedia[0].Cylinders          = cylinders;
                            sidecar.BlockMedia[0].CylindersSpecified = true;
                            sidecar.BlockMedia[0].Heads                    = heads;
                            sidecar.BlockMedia[0].HeadsSpecified           = true;
                            sidecar.BlockMedia[0].SectorsPerTrack          = sectors;
                            sidecar.BlockMedia[0].SectorsPerTrackSpecified = true;
                        }

                        UpdateStatus?.Invoke("Writing metadata sidecar");

                        var xmlFs = new FileStream(_outputPrefix + ".cicm.xml", FileMode.Create);

                        var xmlSer = new XmlSerializer(typeof(CICMMetadataType));
                        xmlSer.Serialize(xmlFs, sidecar);
                        xmlFs.Close();
                    }

                    UpdateStatus?.Invoke("");

                    UpdateStatus?.
                    Invoke($"Took a total of {(end - start).TotalSeconds:F3} seconds ({totalDuration / 1000:F3} processing commands, {totalChkDuration / 1000:F3} checksumming, {imageWriteDuration:F3} writing, {(closeEnd - closeStart).TotalSeconds:F3} closing).");

                    UpdateStatus?.
                    Invoke($"Average speed: {((double)blockSize * (double)(blocks + 1)) / 1048576 / (totalDuration / 1000):F3} MiB/sec.");

                    if (maxSpeed > 0)
                    {
                        UpdateStatus?.Invoke($"Fastest speed burst: {maxSpeed:F3} MiB/sec.");
                    }

                    if (minSpeed > 0 &&
                        minSpeed < double.MaxValue)
                    {
                        UpdateStatus?.Invoke($"Slowest speed burst: {minSpeed:F3} MiB/sec.");
                    }

                    UpdateStatus?.Invoke($"{_resume.BadBlocks.Count} sectors could not be read.");

                    if (_resume.BadBlocks.Count > 0)
                    {
                        _resume.BadBlocks.Sort();
                    }

                    UpdateStatus?.Invoke("");
                }

                Statistics.AddMedia(mediaType, true);
            }
            else
            {
                StoppingErrorMessage?.Invoke("Unable to communicate with ATA device.");
            }
        }
    }
}
 public Hashes(IEnumerable <HashedFingerprint> fingerprints, double durationInSeconds, MediaType mediaType, DateTime relativeTo, IEnumerable <string> origins, string streamId) :
     this(fingerprints,
          durationInSeconds,
          mediaType,
          relativeTo,
          origins,
          streamId,
          emptyDictionary,
          0)
 {
 }
		/// <summary>
		/// Gets the data for the cached image with the given dimensions. In case of
		/// a cache miss null is returned.
		/// </summary>
		/// <param name="id">The id</param>
		/// <param name="width">The width of the image</param>
		/// <param name="height">The optional height of the image</param>
		/// <param name="type">The media type</param>
		/// <returns>The binary data, null in case of a cache miss</returns>
		public virtual byte[] Get(Guid id, int width, int? height, MediaType type = MediaType.Media) {
			var path = GetPath(id, false, width, height, type) ;

			if (File.Exists(path))
				return File.ReadAllBytes(path) ;
			return null ;
		}