/// <summary> /// Converts the <paramref name="document"/> into a <see cref="DicomDataset"/> /// </summary> /// <param name="document"></param> /// <returns></returns> public static DicomDataset BuildDicomDataset(BsonDocument document) { var dataset = new DicomDataset(); foreach (BsonElement element in document) { if (_ignoredBsonKeys.Contains(element.Name)) { continue; } if (element.Name.Contains("PrivateCreator")) { DicomTag creatorTag = DicomTag.Parse(element.Name); dataset.Add(new DicomLongString(new DicomTag(creatorTag.Group, creatorTag.Element), element.Value["val"].AsString)); continue; } DicomTag tag = TryParseTag(dataset, element); DicomVR vr = TryParseVr(element.Value); if (vr == null) { dataset.Add(CreateDicomItem(tag, element.Value)); } else { dataset.Add(CreateDicomItem(tag, element.Value["val"], vr)); } } return(dataset); }
private void FillSequenceFromElementRef(DicomDataset rootEleList) { try { DicomVR vr = _element.ValueRepresentation; if (vr == DicomVR.SQ) { Sequence = new DSequence(this); DicomSequence sequence = _element as DicomSequence; for (int i = 0; i < sequence.Items.Count; i++) { DicomDataset list = sequence.Items[i]; DElementList dlist = new DElementList(list, rootEleList); Sequence._add(dlist); } } } catch (Exception err) { DElement errEle = new DElement(_tag, _vr); LogMgt.Logger.Write(err.ToString()); } }
private bool IsPrivateSequenceBad(IByteSource source) { source.Mark(); try { var group = source.GetUInt16(); var element = source.GetUInt16(); var tag = new DicomTag(group, element); var length = source.GetUInt32(); group = source.GetUInt16(); element = source.GetUInt16(); tag = new DicomTag(group, element); byte[] bytes = source.GetBytes(2); string vr = Encoding.UTF8.GetString(bytes, 0, bytes.Length); DicomVR dummy; if (DicomVR.TryParse(vr, out dummy)) { return(!_explicit); } // unable to parse VR if (_explicit) { return(true); } } finally { source.Rewind(); } return(false); }
public void OnElement(IByteSource source, DicomTag tag, DicomVR vr, IByteBuffer data) { if (_callbacks.TryGetValue(tag, out EventHandler <DicomReaderEventArgs> handler)) { handler(this, new DicomReaderEventArgs(source.Marker, tag, vr, data)); } }
public static string DecodeString(string[] specificCharacterSets, string vrs, byte[] bytes) { var dicomStringDecoder = StringDecoder.Get(specificCharacterSets); var vr = DicomVR.Lookup(vrs); return(dicomStringDecoder.Decode(vr, bytes)); }
private void ReadBulkData ( DicomTag tag, DicomVR vr, JsonTextReader reader, DicomDataset dataset, int level ) { Dicom.IO.Buffer.BulkDataUriByteBuffer data = null; if (reader.Read( )) { string uri = (string)reader.Value; if (!string.IsNullOrEmpty(uri)) { data = new Dicom.IO.Buffer.BulkDataUriByteBuffer(uri); } if (tag == DicomTag.PixelData && level == 0) { var pixelData = DicomPixelData.Create(dataset, true); //2nd parameter is true since we are adding new data here pixelData.AddFrame(data); } else { dataset.AddOrUpdate <Dicom.IO.Buffer.IByteBuffer> (vr, tag, data); } } }
public UpdateDicomElementItem(DicomDataset dataset, DicomVR dicomVR, DicomTag tag, string[] values) { Dataset = dataset; VR = dicomVR; Tag = tag; Values = values; }
protected virtual void WriteVR_Default(DicomDataset ds, DicomElement element, XmlWriter writer) { DicomVR dicomVr = element.ValueRepresentation; for (int index = 0; index < element.Count; index++) { writer.WriteStartElement(Constants.ATTRIBUTE_VALUE_NAME); WriteNumberAttrib(writer, index); if (dicomVr.Equals(DicomVR.AT)) { var atElement = ds.GetSingleValueOrDefault <DicomElement> (element.Tag, null); if (null != atElement) { var tagValue = atElement.Get <DicomTag> ( ); string stringValue = tagValue.ToString("J", null); writer.WriteString(stringValue); } else { writer.WriteString(string.Empty); } } else { writer.WriteString(GetTrimmedString(ds.GetValueOrDefault(element.Tag, index, string.Empty))); } writer.WriteEndElement( ); } }
public AnonymizerVRRule(DicomVR vr, string method, string description, IAnonymizerProcessorFactory processorFactory, JObject ruleSetting = null) : base(method, description, processorFactory, ruleSetting) { EnsureArg.IsNotNull(vr, nameof(vr)); VR = vr; }
private void ReadInlineBinary ( DicomTag tag, DicomVR vr, JsonTextReader reader, DicomDataset dataset, int level ) { if (reader.Read( )) { Dicom.IO.Buffer.MemoryByteBuffer buffer = null; string base64 = (string)reader.Value; if (!string.IsNullOrEmpty(base64)) { buffer = new Dicom.IO.Buffer.MemoryByteBuffer(System.Convert.FromBase64String(base64)); } if (tag == DicomTag.PixelData && level == 0) { var pixelData = DicomPixelData.Create(dataset, true); //2nd parameter is true since we are adding new data here pixelData.AddFrame(buffer); } else { dataset.AddOrUpdate <Dicom.IO.Buffer.IByteBuffer> (vr, tag, buffer); } } }
public DicomReaderEventArgs(long position, DicomTag tag, DicomVR vr, IByteBuffer data) { Position = position; Tag = tag; VR = vr; Data = data; }
private static bool IsPrivateSequenceBad(IByteSource source, bool isExplicitVR) { source.Mark(); try { // Skip "item" tags; continue skipping until length is non-zero (#223) while (new DicomTag(source.GetUInt16(), source.GetUInt16()) == DicomTag.Item // group, element & source.GetUInt32() == 0) // length (using & instead of && enforces RHS to be evaluated regardless of LHS) { } source.GetUInt16(); // group source.GetUInt16(); // element var bytes = source.GetBytes(2); var vr = Encoding.UTF8.GetString(bytes, 0, bytes.Length); DicomVR dummy; if (DicomVR.TryParse(vr, out dummy)) { return(!isExplicitVR); } // unable to parse VR if (isExplicitVR) { return(true); } } finally { source.Rewind(); } return(false); }
public void OnBeginFragmentSequence(IByteSource source, DicomTag tag, DicomVR vr) { foreach (IDicomReaderObserver observer in _observers) { observer.OnBeginFragmentSequence(source, tag, vr); } }
public ExtendedQueryTagFilterDetails(int tagKey, QueryTagLevel tagLevel, DicomVR vr, DicomTag tag) { Key = tagKey; VR = vr; Level = tagLevel; Tag = tag; }
private void ResetState() { _state = ParseState.Tag; _tag = null; _vr = null; _length = 0; }
public void OnElement(IByteSource source, DicomTag tag, DicomVR vr, IByteBuffer data) { foreach (IDicomReaderObserver observer in _observers) { observer.OnElement(source, tag, vr, data); } }
private static void ValidateVRCode(DicomTag tag, string vrCode, string tagPath) { DicomVR dicomVR = string.IsNullOrWhiteSpace(vrCode) ? null : ParseVRCode(vrCode, tagPath); if (tag.DictionaryEntry != DicomDictionary.UnknownTag) { // if VR is specified for knownTag, validate if (dicomVR != null) { if (!tag.DictionaryEntry.ValueRepresentations.Contains(dicomVR)) { // not a valid VR throw new ExtendedQueryTagEntryValidationException( string.Format(CultureInfo.InvariantCulture, DicomCoreResource.UnsupportedVRCodeOnTag, vrCode, tagPath, tag.GetDefaultVR())); } } else { // otherwise, get default one dicomVR = tag.GetDefaultVR(); } } else { // for unknown tag, vrCode is required if (dicomVR == null) { throw new ExtendedQueryTagEntryValidationException( string.Format(CultureInfo.InvariantCulture, DicomCoreResource.MissingVRCode, tagPath)); } } EnsureVRIsSupported(dicomVR, tagPath); }
/// <summary> /// Write tag header. /// </summary> /// <param name="tag">DICOM tag.</param> /// <param name="vr">Value Representation.</param> /// <param name="length">Element length.</param> private void WriteTagHeader(DicomTag tag, DicomVR vr, uint length) { _target.Write(tag.Group); _target.Write(tag.Element); if (Syntax.IsExplicitVR && vr != DicomVR.NONE) { // Comply with CP-1066 (#597) if (vr.Is16bitLength && length > 0xfffe) { vr = DicomVR.UN; } _target.Write((byte)vr.Code[0]); _target.Write((byte)vr.Code[1]); if (vr.Is16bitLength) { _target.Write((ushort)length); } else { _target.Write((ushort)0); _target.Write(length); } } else { _target.Write(length); } }
private void ValidateByteBufferLength(DicomVR dicomVR, string name, IByteBuffer value) { if (value?.Size != ExpectedLength) { throw ElementValidationExceptionFactory.CreateUnexpectedLengthException(name, dicomVR, ExpectedLength); } }
/// <summary> /// Write tag header. /// </summary> /// <param name="tag">DICOM tag.</param> /// <param name="vr">Value Representation.</param> /// <param name="length">Element length.</param> private void WriteTagHeader(DicomTag tag, DicomVR vr, uint length) { _target.Write(tag.Group); _target.Write(tag.Element); if (_syntax.IsExplicitVR && vr != DicomVR.NONE) { _target.Write((byte)vr.Code[0]); _target.Write((byte)vr.Code[1]); if (vr.Is16bitLength) { _target.Write((ushort)length); } else { _target.Write((ushort)0); _target.Write(length); } } else { _target.Write(length); } }
private void AddOrUpdateDicomItem(DicomDataset dataset, DicomVR vr, DicomTag tag, string[] values) { string charset = _currentFile.Dataset.GetSingleValueOrDefault(DicomTag.SpecificCharacterSet, "ISO_IR 192"); try { if (vr == DicomVR.OB || vr == DicomVR.UN) { byte[] temp = new byte[values.Length]; for (int i = 0; i < values.Length; i++) { temp[i] = byte.Parse(values[i]); } dataset.AddOrUpdate(vr, tag, DicomEncoding.GetEncoding(charset), temp); } else { dataset.AddOrUpdate(vr, tag, DicomEncoding.GetEncoding(charset), values); } } catch (System.Exception e) { _logger.Error(e); return; } _currentItem.UpdateItem(dataset.GetDicomItem <DicomElement>(tag)); }
public ElementValidationException(string name, DicomVR vr, string value, ValidationErrorCode errorCode, string message) : base(message) { Name = EnsureArg.IsNotNull(name, nameof(name)); VR = EnsureArg.IsNotNull(vr, nameof(vr)); Value = EnsureArg.IsNotNull(value, nameof(value)); ErrorCode = EnsureArg.EnumIsDefined(errorCode, nameof(errorCode)); }
private static bool IsPrivateSequenceBad(IByteSource source, bool isExplicitVR) { source.Mark(); try { source.GetUInt16(); // group source.GetUInt16(); // element source.GetUInt32(); // length source.GetUInt16(); // group source.GetUInt16(); // element var bytes = source.GetBytes(2); var vr = Encoding.UTF8.GetString(bytes, 0, bytes.Length); DicomVR dummy; if (DicomVR.TryParse(vr, out dummy)) { return(!isExplicitVR); } // unable to parse VR if (isExplicitVR) { return(true); } } finally { source.Rewind(); } return(false); }
private void Add(ushort group, ushort element, DicomVR vr, string value) { var key = String.Format("{0}{1}", group.ToString("X4"), element.ToString("X4")); if (IsString(vr)) { var values = new string[1]; values[0] = value; _attributes[key] = new { vr = vr.ToString(), Value = values }; } else if (IsFloat(vr)) { var values = new double[1]; values[0] = Double.Parse(value); _attributes[key] = new { vr = vr.ToString(), Value = values }; } else if (IsInteger(vr)) { var values = new long[1]; values[0] = Int64.Parse(value); _attributes[key] = new { vr = vr.ToString(), Value = values }; } else if (IsName(vr)) { var pnValues = new object[1]; pnValues[0] = new { Alphabetic = value }; _attributes[key] = new { vr = vr.ToString(), Value = pnValues }; } else if (IsBase64(vr)) { // todo: base 64 encoding return; } else if (IsSequence(vr)) { // todo: sequence encoding return; } }
private bool IsSequence(DicomVR vr) { if (vr == DicomVR.SQ) { return(true); } return(false); }
private void ResetState() { this.parseStage = ParseStage.Tag; this._tag = null; this._entry = null; this._vr = null; this.length = 0; }
private void ResetState() { _parseStage = ParseStage.Tag; _tag = null; _entry = null; _vr = null; _length = 0; }
private void ValidateStringLength(DicomVR dicomVR, string name, string value) { value = value ?? ""; if (value.Length != ExpectedLength) { throw ElementValidationExceptionFactory.CreateUnexpectedLengthException(name, dicomVR, value, ExpectedLength); } }
public void OnElement_ValidData_AddsCorrectTypeToDataset(DicomTag tag, DicomVR vr, string data, Type expected) { var dataset = new DicomDataset(); var observer = new DicomDatasetReaderObserver(dataset); var buffer = new MemoryByteBuffer(Encoding.ASCII.GetBytes(data)); observer.OnElement(null, tag, vr, buffer); Assert.IsType(expected, dataset.First()); }
public void GivenDicomTagWithDifferentVR_WhenGetSingleOrDefaultIsCalled_ThenShouldReturnNull() { DicomTag tag = DicomTag.AbortReason; DicomVR expectedVR = DicomVR.CS; DicomElement element = new DicomLongString(tag, "Value"); _dicomDataset.Add(element); Assert.Null(_dicomDataset.GetSingleValueOrDefault <string>(tag, expectedVR)); }
public void OnBeginFragmentSequence(IByteSource source, DicomTag tag, DicomVR vr) { if (vr == DicomVR.OB) _fragment = new DicomOtherByteFragment(tag); else if (vr == DicomVR.OW) _fragment = new DicomOtherWordFragment(tag); else throw new DicomDataException("Unexpected VR found for DICOM fragment sequence: {0}", vr.Code); DicomDataset ds = _datasets.Peek(); ds.Add(_fragment); }
public void OnBeginFragmentSequence(IByteSource source, DicomTag tag, DicomVR vr) { _log.Log( _level, "{marker:x8}: {padding}{tag} {vrCode} {tagDictionaryEntryName}", source.Marker, _pad, tag, vr.Code, tag.DictionaryEntry.Name); IncreaseDepth(); }
public void OnElement(IByteSource source, DicomTag tag, DicomVR vr, IByteBuffer data) { _log.Log( _level, "{marker:x8}: {padding}{tag} {vrCode} {tagDictionaryEntryName} [{size}]", source.Marker, _pad, tag, vr.Code, tag.DictionaryEntry.Name, data.Size); }
public void BeginRead_ValidExplicitVRData_YieldsSuccess(DicomTag tag, DicomVR vr, string data, byte[] bytes) { var stream = new MemoryStream(bytes); var source = new StreamByteSource(stream); var reader = new DicomReader { IsExplicitVR = true }; var observer = new LastElementObserver(); var result = reader.EndRead(reader.BeginRead(source, observer, null, null, null)); Assert.Equal(DicomReaderResult.Success, result); Assert.Equal(tag, observer.Tag); Assert.Equal(vr, observer.VR); Assert.Equal(data, observer.Data); }
public void OnElement(IByteSource source, DicomTag tag, DicomVR vr, IByteBuffer data) { DicomElement element; switch (vr.Code) { case "AE": element = new DicomApplicationEntity(tag, data); break; case "AS": element = new DicomAgeString(tag, data); break; case "AT": element = new DicomAttributeTag(tag, data); break; case "CS": element = new DicomCodeString(tag, data); break; case "DA": element = new DicomDate(tag, data); break; case "DS": element = new DicomDecimalString(tag, data); break; case "DT": element = new DicomDateTime(tag, data); break; case "FD": element = new DicomFloatingPointDouble(tag, data); break; case "FL": element = new DicomFloatingPointSingle(tag, data); break; case "IS": element = new DicomIntegerString(tag, data); break; case "LO": element = new DicomLongString(tag, _encodings.Peek(), data); break; case "LT": element = new DicomLongText(tag, _encodings.Peek(), data); break; case "OB": element = new DicomOtherByte(tag, data); break; case "OD": element = new DicomOtherDouble(tag, data); break; case "OF": element = new DicomOtherFloat(tag, data); break; case "OW": element = new DicomOtherWord(tag, data); break; case "PN": element = new DicomPersonName(tag, _encodings.Peek(), data); break; case "SH": element = new DicomShortString(tag, _encodings.Peek(), data); break; case "SL": element = new DicomSignedLong(tag, data); break; case "SS": element = new DicomSignedShort(tag, data); break; case "ST": element = new DicomShortText(tag, _encodings.Peek(), data); break; case "TM": element = new DicomTime(tag, data); break; case "UC": element = new DicomUnlimitedCharacters(tag, _encodings.Peek(), data); break; case "UI": element = new DicomUniqueIdentifier(tag, data); break; case "UL": element = new DicomUnsignedLong(tag, data); break; case "UN": element = new DicomUnknown(tag, data); break; case "UR": element = new DicomUniversalResource(tag, _encodings.Peek(), data); break; case "US": element = new DicomUnsignedShort(tag, data); break; case "UT": element = new DicomUnlimitedText(tag, _encodings.Peek(), data); break; default: throw new DicomDataException("Unhandled VR in DICOM parser observer: {0}", vr.Code); } if (element.Tag == DicomTag.SpecificCharacterSet) { Encoding encoding = _encodings.Peek(); if (element.Count > 0) encoding = DicomEncoding.GetEncoding(element.Get<string>(0)); _encodings.Pop(); _encodings.Push(encoding); } DicomDataset ds = _datasets.Peek(); ds.Add(element); }
public void OnBeginFragmentSequence(IByteSource source, DicomTag tag, DicomVR vr) { _stack.Push(new DicomReaderEventArgs(source.Marker, tag, vr, null)); }
private void WriteTagHeader(DicomTag tag, DicomVR vr, uint length) { _target.Write(tag.Group); _target.Write(tag.Element); if (_syntax.IsExplicitVR && vr != DicomVR.NONE) { _target.Write((byte)vr.Code[0]); _target.Write((byte)vr.Code[1]); if (vr.Is16bitLength) { _target.Write((ushort)length); } else { _target.Write((ushort)0); _target.Write(length); } } else { _target.Write(length); } }
private async Task<bool> ParseValueAsync(IByteSource source) { if (this.parseStage == ParseStage.Value) { // check dictionary for VR after reading length to handle 16-bit lengths // check before reading value to handle SQ elements var parsedVR = this._vr; // check dictionary for VR after reading length to handle 16-bit lengths // check before reading value to handle SQ elements if (this._vr == DicomVR.Implicit || (this._vr == DicomVR.UN && this.isExplicitVR)) { var entry = this.dictionary[this._tag]; if (entry != null) { this._vr = entry.ValueRepresentations.FirstOrDefault(); } if (this._vr == null) { this._vr = DicomVR.UN; } } if (this._tag == DicomTag.ItemDelimitationItem) { // end of sequence item return false; } while (this._vr == DicomVR.SQ && this._tag.IsPrivate) { if (!IsPrivateSequence(source)) { this._vr = DicomVR.UN; break; } if (IsPrivateSequenceBad(source, this.isExplicitVR)) { this.badPrivateSequence = true; this.isExplicitVR = !this.isExplicitVR; } break; } if (this._vr == DicomVR.SQ) { // start of sequence this.observer.OnBeginSequence(source, this._tag, this.length); this.parseStage = ParseStage.Tag; if (this.length != UndefinedLength) { this._implicit = false; source.PushMilestone(this.length); } else { this._implicit = true; } var last = source.Position; // Conformance with CP-246 (#177) var needtoChangeEndian = false; if (parsedVR == DicomVR.UN && !this._tag.IsPrivate) { this._implicit = true; needtoChangeEndian = source.Endian == Endian.Big; } if (needtoChangeEndian) { source.Endian = Endian.Little; } await this.ParseItemSequenceAsync(source).ConfigureAwait(false); if (needtoChangeEndian) { source.Endian = Endian.Big; } // Aeric Sylvan - https://github.com/rcd/fo-dicom/issues/62#issuecomment-46248073 // Fix reading of SQ with parsed VR of UN if (source.Position > last || this.length == 0) { return true; } this.parseStage = ParseStage.Value; this._vr = parsedVR; } if (this.length == UndefinedLength) { this.observer.OnBeginFragmentSequence(source, this._tag, this._vr); this.parseStage = ParseStage.Tag; await this.ParseFragmentSequenceAsync(source).ConfigureAwait(false); return true; } if (!source.Require(this.length)) { this.result = DicomReaderResult.Suspended; return false; } var buffer = await source.GetBufferAsync(this.length).ConfigureAwait(false); if (!this._vr.IsString) { buffer = EndianByteBuffer.Create(buffer, source.Endian, this._vr.UnitSize); } this.observer.OnElement(source, this._tag, this._vr, buffer); // parse private creator value and add to lookup table if (this._tag.IsPrivate && this._tag.Element != 0x0000 && this._tag.Element <= 0x00ff) { var creator = DicomEncoding.Default.GetString(buffer.Data, 0, buffer.Data.Length) .TrimEnd((char)DicomVR.LO.PaddingValue); var card = (uint)(this._tag.Group << 16) + this._tag.Element; lock (this.locker) { this._private[card] = creator; } } this.ResetState(); } return true; }
public void OnElement(IByteSource source, DicomTag tag, DicomVR vr, IByteBuffer data) { _log.Log(_level, "{0:x8}: {1}{2} {3} {4} [{5}]", source.Marker, _pad, tag, vr.Code, tag.DictionaryEntry.Name, data.Size); }
public void OnElement(IByteSource source, DicomTag tag, DicomVR vr, IByteBuffer data) { EventHandler<DicomReaderEventArgs> handler; if (_callbacks.TryGetValue(tag, out handler)) handler(this, new DicomReaderEventArgs(source.Marker, tag, vr, data)); }
public void OnBeginFragmentSequence(IByteSource source, DicomTag tag, DicomVR vr) { }
public void OnElement(IByteSource source, DicomTag tag, DicomVR vr, IByteBuffer data) { this.Tag = tag; this.VR = vr; this.Data = Encoding.UTF8.GetString(data.Data); }
private bool ParseVR(IByteSource source) { while (this.parseStage == ParseStage.VR) { if (this._tag == DicomTag.Item || this._tag == DicomTag.ItemDelimitationItem || this._tag == DicomTag.SequenceDelimitationItem) { this._vr = DicomVR.NONE; this.parseStage = ParseStage.Length; break; } if (this.isExplicitVR) { if (!source.Require(2)) { this.result = DicomReaderResult.Suspended; return false; } source.Mark(); var bytes = source.GetBytes(2); var vr = Encoding.UTF8.GetString(bytes, 0, bytes.Length); if (string.IsNullOrWhiteSpace(vr)) { if (this._entry != null) { this._vr = this._entry.ValueRepresentations.FirstOrDefault(); } } else if (!DicomVR.TryParse(vr, out this._vr)) { // unable to parse VR; rewind VR bytes for continued attempt to interpret the data. this._vr = DicomVR.Implicit; source.Rewind(); } } else { if (this._entry != null) { if (this._entry == DicomDictionary.UnknownTag) { this._vr = DicomVR.UN; } else if (this._entry.ValueRepresentations.Contains(DicomVR.OB) && this._entry.ValueRepresentations.Contains(DicomVR.OW)) { this._vr = DicomVR.OW; // ??? } else { this._vr = this._entry.ValueRepresentations.FirstOrDefault(); } } } if (this._vr == null) { this._vr = DicomVR.UN; } this.parseStage = ParseStage.Length; if (this._vr == DicomVR.UN) { if (this._tag.Element == 0x0000) { // Group Length to UL this._vr = DicomVR.UL; break; } if (this.isExplicitVR) { break; } } if (this._tag.IsPrivate) { if (this._tag.Element != 0x0000 && this._tag.Element <= 0x00ff && this._vr == DicomVR.UN) { this._vr = DicomVR.LO; // force private creator to LO } } } return true; }
private void ParseDataset(IByteSource source, object state) { try { _result = DicomReaderResult.Processing; while (!source.IsEOF && !source.HasReachedMilestone() && _result == DicomReaderResult.Processing) { if (_state == ParseState.Tag) { source.Mark(); if (!source.Require(4, ParseDataset, state)) { _result = DicomReaderResult.Suspended; return; } ushort group = source.GetUInt16(); ushort element = source.GetUInt16(); DicomPrivateCreator creator = null; if (group.IsOdd() && element > 0x00ff) { string pvt = null; uint card = (uint)(group << 16) + (uint)(element >> 8); if (_private.TryGetValue(card, out pvt)) creator = Dictionary.GetPrivateCreator(pvt); } _tag = new DicomTag(group, element, creator); if (_stop != null && _tag.CompareTo(_stop) >= 0) { _result = DicomReaderResult.Stopped; return; } _state = ParseState.VR; } while (_state == ParseState.VR) { if (_tag == DicomTag.Item || _tag == DicomTag.ItemDelimitationItem || _tag == DicomTag.SequenceDelimitationItem) { _vr = DicomVR.NONE; _state = ParseState.Length; break; } if (IsExplicitVR) { if (!source.Require(2, ParseDataset, state)) { _result = DicomReaderResult.Suspended; return; } byte[] bytes = source.GetBytes(2); string vr = Encoding.UTF8.GetString(bytes, 0, bytes.Length); try { _vr = DicomVR.Parse(vr); } catch { // unable to parse VR _vr = DicomVR.UN; } } else { DicomDictionaryEntry entry = Dictionary[_tag]; if (entry != null) { if (entry == DicomDictionary.UnknownTag) _vr = DicomVR.UN; else if (entry.ValueRepresentations.Contains(DicomVR.OB) && entry.ValueRepresentations.Contains(DicomVR.OW)) _vr = DicomVR.OW; // ??? else _vr = entry.ValueRepresentations.FirstOrDefault(); } } if (_vr == null) _vr = DicomVR.UN; _state = ParseState.Length; if (_vr == DicomVR.UN) { if (_tag.Element == 0x0000) { // Group Length to UL _vr = DicomVR.UL; break; } else if (IsExplicitVR) { break; } } if (_tag.IsPrivate) { if (_tag.Element != 0x0000 && _tag.Element <= 0x00ff && _vr == DicomVR.UN) _vr = DicomVR.LO; // force private creator to LO } } while (_state == ParseState.Length) { if (_tag == DicomTag.Item || _tag == DicomTag.ItemDelimitationItem || _tag == DicomTag.SequenceDelimitationItem) { if (!source.Require(4, ParseDataset, state)) { _result = DicomReaderResult.Suspended; return; } _length = source.GetUInt32(); _state = ParseState.Value; break; } if (IsExplicitVR) { if (_vr.Is16bitLength) { if (!source.Require(2, ParseDataset, state)) { _result = DicomReaderResult.Suspended; return; } _length = source.GetUInt16(); } else { if (!source.Require(6, ParseDataset, state)) { _result = DicomReaderResult.Suspended; return; } source.Skip(2); _length = source.GetUInt32(); } } else { if (!source.Require(4, ParseDataset, state)) { _result = DicomReaderResult.Suspended; return; } _length = source.GetUInt32(); // assume that undefined length in implicit dataset is SQ if (_length == UndefinedLength && _vr == DicomVR.UN) _vr = DicomVR.SQ; } _state = ParseState.Value; } if (_state == ParseState.Value) { // check dictionary for VR after reading length to handle 16-bit lengths // check before reading value to handle SQ elements if (_vr == DicomVR.UN && IsExplicitVR) { var entry = Dictionary[_tag]; if (entry != null) _vr = entry.ValueRepresentations.FirstOrDefault(); if (_vr == null) _vr = DicomVR.UN; } if (_tag == DicomTag.ItemDelimitationItem) { // end of sequence item return; } while (_vr == DicomVR.SQ && _tag.IsPrivate) { if (!IsPrivateSequence(source)) { _vr = DicomVR.UN; break; } if (IsPrivateSequenceBad(source)) { _badPrivateSequence = true; _explicit = !_explicit; } break; } if (_vr == DicomVR.SQ) { // start of sequence _observer.OnBeginSequence(source, _tag, _length); _state = ParseState.Tag; if (_length != UndefinedLength) { _implicit = false; source.PushMilestone(_length); } else _implicit = true; PushState(state); ParseItemSequence(source, null); continue; } if (_length == UndefinedLength) { _observer.OnBeginFragmentSequence(source, _tag, _vr); _state = ParseState.Tag; PushState(state); ParseFragmentSequence(source, null); continue; } if (!source.Require(_length, ParseDataset, state)) { _result = DicomReaderResult.Suspended; return; } IByteBuffer buffer = source.GetBuffer(_length); if (!_vr.IsString) buffer = EndianByteBuffer.Create(buffer, source.Endian, _vr.UnitSize); _observer.OnElement(source, _tag, _vr, buffer); // parse private creator value and add to lookup table if (_tag.IsPrivate && _tag.Element != 0x0000 && _tag.Element <= 0x00ff) { var creator = DicomEncoding.Default.GetString(buffer.Data, 0, buffer.Data.Length).TrimEnd((char)DicomVR.LO.PaddingValue); var card = (uint)(_tag.Group << 16) + (uint)(_tag.Element); _private[card] = creator; } ResetState(); } } if (source.HasReachedMilestone()) { // end of explicit length sequence item source.PopMilestone(); return; } if (_result != DicomReaderResult.Processing) return; // end of processing _result = DicomReaderResult.Success; } catch (Exception e) { _exception = e; _result = DicomReaderResult.Error; } finally { if (_result != DicomReaderResult.Processing && _result != DicomReaderResult.Suspended) { _async.Set(); } } }
public void OnElement(IByteSource source, DicomTag tag, DicomVR vr, IByteBuffer data) { foreach (IDicomReaderObserver observer in _observers) observer.OnElement(source, tag, vr, data); }
public void OnBeginFragmentSequence(IByteSource source, DicomTag tag, DicomVR vr) { _log.Log(_level, "{0:x8}: {1}{2} {3} {4}", source.Marker, _pad, tag, vr.Code, tag.DictionaryEntry.Name); IncreaseDepth(); }
public void OnBeginFragmentSequence(IByteSource source, DicomTag tag, DicomVR vr) { foreach (IDicomReaderObserver observer in _observers) observer.OnBeginFragmentSequence(source, tag, vr); }
public void OnElement(IByteSource source, DicomTag tag, DicomVR vr, IByteBuffer data) { }
private bool ParseLength(IByteSource source) { while (this.parseStage == ParseStage.Length) { if (this._tag == DicomTag.Item || this._tag == DicomTag.ItemDelimitationItem || this._tag == DicomTag.SequenceDelimitationItem) { if (!source.Require(4)) { this.result = DicomReaderResult.Suspended; return false; } this.length = source.GetUInt32(); this.parseStage = ParseStage.Value; break; } if (this.isExplicitVR) { if (this._vr == DicomVR.Implicit) { if (!source.Require(4)) { this.result = DicomReaderResult.Suspended; return false; } this.length = source.GetUInt32(); // assume that undefined length in implicit VR element is SQ if (this.length == UndefinedLength) { this._vr = DicomVR.SQ; } } else if (this._vr.Is16bitLength) { if (!source.Require(2)) { this.result = DicomReaderResult.Suspended; return false; } this.length = source.GetUInt16(); } else { if (!source.Require(6)) { this.result = DicomReaderResult.Suspended; return false; } source.Skip(2); this.length = source.GetUInt32(); // CP-246 (#177) handling // assume that Undefined Length in explicit datasets with VR UN are sequences // According to CP-246 the sequence shall be handled as ILE, but this will be handled later... // in the current code this needs to be restricted to privates if (this.length == UndefinedLength && this._vr == DicomVR.UN && this._tag.IsPrivate) { this._vr = DicomVR.SQ; } } } else { if (!source.Require(4)) { this.result = DicomReaderResult.Suspended; return false; } this.length = source.GetUInt32(); // assume that undefined length in implicit dataset is SQ if (this.length == UndefinedLength && this._vr == DicomVR.UN) { this._vr = DicomVR.SQ; } } this.parseStage = ParseStage.Value; } return true; }