changeset 6809:3f5309b92016 streaming

created branch streaming
author Sebastien Jodogne <s.jodogne@gmail.com>
date Tue, 19 May 2026 14:00:46 +0200
parents b60fb4f30c4b
children 9b416c2b0471
files OrthancFramework/Sources/HttpServer/HttpOutput.cpp OrthancFramework/Sources/HttpServer/HttpOutput.h OrthancServer/Sources/OrthancRestApi/OrthancRestResources.cpp OrthancServer/Sources/ServerContext.cpp OrthancServer/Sources/ServerContext.h OrthancServer/Sources/ServerJobs/ThreadedInstancesLoader.cpp
diffstat 6 files changed, 205 insertions(+), 173 deletions(-) [+]
line wrap: on
line diff
--- a/OrthancFramework/Sources/HttpServer/HttpOutput.cpp	Tue May 19 12:56:29 2026 +0200
+++ b/OrthancFramework/Sources/HttpServer/HttpOutput.cpp	Tue May 19 14:00:46 2026 +0200
@@ -377,7 +377,7 @@
 
 
   void HttpOutput::SendStatus(HttpStatus status,
-                              const char* message,
+                              const void* message,
                               size_t messageSize)
   {
     if (status == HttpStatus_301_MovedPermanently ||
--- a/OrthancFramework/Sources/HttpServer/HttpOutput.h	Tue May 19 12:56:29 2026 +0200
+++ b/OrthancFramework/Sources/HttpServer/HttpOutput.h	Tue May 19 14:00:46 2026 +0200
@@ -158,7 +158,7 @@
     }
 
     void SendStatus(HttpStatus status,
-		    const char* message,
+		    const void* message,
 		    size_t messageSize);
 
     void SendStatus(HttpStatus status);
--- a/OrthancServer/Sources/OrthancRestApi/OrthancRestResources.cpp	Tue May 19 12:56:29 2026 +0200
+++ b/OrthancServer/Sources/OrthancRestApi/OrthancRestResources.cpp	Tue May 19 14:00:46 2026 +0200
@@ -26,7 +26,9 @@
 
 #include "OrthancRestApi.h"
 
+#include "../../../OrthancFramework/Sources/CompatibilityMath.h"
 #include "../../../OrthancFramework/Sources/Compression/GzipCompressor.h"
+#include "../../../OrthancFramework/Sources/DataSource/StorageAreaDataSource.h"
 #include "../../../OrthancFramework/Sources/DicomFormat/DicomImageInformation.h"
 #include "../../../OrthancFramework/Sources/DicomParsing/DicomWebJsonVisitor.h"
 #include "../../../OrthancFramework/Sources/DicomParsing/FromDcmtkBridge.h"
@@ -38,7 +40,6 @@
 #include "../../../OrthancFramework/Sources/Logging.h"
 #include "../../../OrthancFramework/Sources/MultiThreading/Semaphore.h"
 #include "../../../OrthancFramework/Sources/SerializationToolbox.h"
-#include "../../../OrthancFramework/Sources/CompatibilityMath.h"
 
 #include "../OrthancConfiguration.h"
 #include "../Search/DatabaseLookup.h"
@@ -2379,13 +2380,14 @@
 
       if (hasRangeHeader)
       {
-        std::string fragment;
-        context.ReadAttachmentRange(fragment, info, range, uncompress);
+        std::unique_ptr<StorageAreaDataSource::Range> fragment(
+          StorageAreaDataSource::ReadRange(
+            context.GetStorageAreaReader(), info, range, uncompress, context.IsCheckMD5()));
 
         uint64_t fullSize = (uncompress ? info.GetUncompressedSize() : info.GetCompressedSize());
         call.GetOutput().GetLowLevelOutput().SetContentType(MimeType_Binary);
         call.GetOutput().GetLowLevelOutput().AddHeader("Content-Range", range.FormatHttpContentRange(fullSize));
-        call.GetOutput().GetLowLevelOutput().SendStatus(HttpStatus_206_PartialContent, fragment);
+        call.GetOutput().GetLowLevelOutput().SendStatus(HttpStatus_206_PartialContent, fragment->GetData(), fragment->GetSize());
       }
       else if (uncompress ||
                info.GetCompressionType() == CompressionType_None)
@@ -2395,9 +2397,11 @@
       else
       {
         // Access to the raw attachment (which is compressed)
-        std::string content;
-        context.ReadAttachment(content, info, false /* don't uncompress */, true /* skip cache */);
-        call.GetOutput().AnswerBuffer(content, MimeType_Binary);
+        std::unique_ptr<StorageAreaDataSource::Range> content(
+          StorageAreaDataSource::ReadAttachment(
+            context.GetStorageAreaReader(), info, false /* don't uncompress */, context.IsCheckMD5()));
+
+        call.GetOutput().AnswerBuffer(content->GetData(), content->GetSize(), MimeType_Binary);
       }
     }
   }
@@ -2575,13 +2579,16 @@
     bool ok = false;
 
     // First check whether the compressed data is correctly stored in the disk
-    std::string data;
-    context.ReadAttachment(data, info, false, true /* skipCache when you absolutely need the compressed data */);
-
-    std::string actualMD5;
-    Toolbox::ComputeMD5(actualMD5, data);
+    std::string compressedMD5;
+
+    {
+      std::unique_ptr<StorageAreaDataSource::Range> compressed(
+        StorageAreaDataSource::ReadAttachment(
+          context.GetStorageAreaReader(), info, false /* don't uncompress */, false /* check MD5 */));
+      Toolbox::ComputeMD5(compressedMD5, compressed->GetData(), compressed->GetSize());
+    }
     
-    if (actualMD5 == info.GetCompressedMD5())
+    if (compressedMD5 == info.GetCompressedMD5())
     {
       // The compressed data is OK. If a compression algorithm was
       // applied to it, now check the MD5 of the uncompressed data.
@@ -2591,9 +2598,16 @@
       }
       else
       {
-        context.ReadAttachment(data, info, true, true /* skipCache when you absolutely need the compressed data */);
-        Toolbox::ComputeMD5(actualMD5, data);
-        ok = (actualMD5 == info.GetUncompressedMD5());
+        std::string uncompressedMD5;
+
+        {
+          std::unique_ptr<StorageAreaDataSource::Range> uncompressed(
+            StorageAreaDataSource::ReadAttachment(
+              context.GetStorageAreaReader(), info, true /* uncompress */, false /* check MD5 */));
+          Toolbox::ComputeMD5(uncompressedMD5, uncompressed->GetData(), uncompressed->GetSize());
+        }
+
+        ok = (uncompressedMD5 == info.GetUncompressedMD5());
       }
     }
 
--- a/OrthancServer/Sources/ServerContext.cpp	Tue May 19 12:56:29 2026 +0200
+++ b/OrthancServer/Sources/ServerContext.cpp	Tue May 19 14:00:46 2026 +0200
@@ -25,6 +25,7 @@
 #include "ServerContext.h"
 
 #include "../../OrthancFramework/Sources/Cache/SharedArchive.h"
+#include "../../OrthancFramework/Sources/DataSource/StorageAreaDataSource.h"
 #include "../../OrthancFramework/Sources/DicomFormat/DicomElement.h"
 #include "../../OrthancFramework/Sources/DicomFormat/DicomStreamReader.h"
 #include "../../OrthancFramework/Sources/DicomNetworking/DicomStoreUserConnection.h"
@@ -39,6 +40,7 @@
 #include "../../OrthancFramework/Sources/Logging.h"
 #include "../../OrthancFramework/Sources/MallocMemoryBuffer.h"
 #include "../../OrthancFramework/Sources/MetricsRegistry.h"
+#include "../../OrthancFramework/Sources/MultiThreading/ThreadPool.h"
 #include "../../OrthancFramework/Sources/SerializationToolbox.h"
 #include "../Plugins/Engine/OrthancPlugins.h"
 
@@ -406,7 +408,8 @@
     readOnly_(readOnly),
     patientLevelEnabled_(true),
     deidentifyLogs_(false),
-    serverStartTimeUtc_(boost::posix_time::second_clock::universal_time())
+    serverStartTimeUtc_(boost::posix_time::second_clock::universal_time()),
+    checkMD5_(true)
   {
     try
     {
@@ -538,6 +541,8 @@
         defaultDicomRetrieveMethod_ = StringToRetrieveMethod(lock.GetConfiguration().GetDicomDefaultRetrieveMethod());
 
         dynamic_cast<DcmtkTranscoder&>(*dcmtkTranscoder_).SetDefaultLossyQuality(lock.GetConfiguration().GetDicomLossyTranscodingQuality());
+
+        checkMD5_ = lock.GetConfiguration().GetBooleanParameter("CheckMD5", true);  // TODO-Streaming - Parameter
       }
 
       jobsEngine_.SetThreadSleep(unitTesting ? 20 : 200);
@@ -552,6 +557,27 @@
 #else
       LOG(INFO) << "Your platform does not support malloc_trim(), not starting the memory trimming thread";
 #endif
+
+      // For streaming
+      {
+        std::unique_ptr<ThreadPool> pool(new ThreadPool);
+        pool->SetCountThreads(4);  // TODO-Streaming - Parameter
+        pool->SetDequeueTimeout(100);
+        pool->Start();
+
+        storageAreaReader_.reset(new DataSourceReader(pool.release(), new StorageAreaDataSource(area_)));
+        storageAreaReader_->CreateCache(256 * 1024 * 1024); // 256 MB - TODO-Streaming - Parameter
+      }
+
+      {
+        std::unique_ptr<ThreadPool> pool(new ThreadPool);
+        pool->SetCountThreads(2);  // TODO-Streaming - Parameter
+        pool->SetDequeueTimeout(100);
+        pool->Start();
+
+        dicomReader_.reset(new DataSourceReader(pool.release(), new DicomDataSource(storageAreaReader_)));
+        dicomReader_->CreateCache(100 * 1024 * 1024); // 100 MB - TODO-Streaming - Parameter
+      }
     }
     catch (OrthancException&)
     {
@@ -1098,8 +1124,17 @@
                                        const FileInfo& attachment,
                                        const std::string& filename)
   {
-    StorageAccessor accessor(area_, storageCache_, GetMetricsRegistry());
-    accessor.AnswerFile(output, attachment, GetFileContentMime(attachment.GetContentType()), filename);
+    std::unique_ptr<StorageAreaDataSource::Range> range(
+      StorageAreaDataSource::ReadAttachment(
+        *storageAreaReader_, attachment, true /* uncompress */, checkMD5_));
+
+    BufferHttpSender sender;
+    sender.SetBuffer(range->GetData(), range->GetSize());
+    sender.SetContentType(GetFileContentMime(attachment.GetContentType()));
+    sender.SetContentFilename(filename.c_str());
+
+    HttpStreamTranscoder transcoder(sender, CompressionType_None);
+    output.AnswerStream(transcoder);
   }
 
 
@@ -1126,13 +1161,18 @@
       return;
     }
 
-    std::string content;
 
     StorageAccessor accessor(area_, storageCache_, GetMetricsRegistry());
-    accessor.Read(content, attachment);
 
     FileInfo modified;
-    accessor.Write(modified, content.empty() ? NULL : content.c_str(), content.size(), attachmentType, compression, storeMD5_, NULL);
+
+    {
+      std::unique_ptr<StorageAreaDataSource::Range> range(
+        StorageAreaDataSource::ReadAttachment(
+          *storageAreaReader_, attachment, true /* uncompress */, checkMD5_));
+
+      accessor.Write(modified, range->GetData(), range->GetSize(), attachmentType, compression, storeMD5_, NULL);
+    }
 
     try
     {
@@ -1260,15 +1300,14 @@
 
     if (LookupAttachment(attachment, FileContentType_DicomUntilPixelData, instanceAttachments))
     {
-      std::string dicom;
+      std::unique_ptr<DicomDataSource::Dicom> dicom(
+        DicomDataSource::ReadWhole(*dicomReader_, attachment, false /* no need for raw buffer */, checkMD5_));
 
       {
-        StorageAccessor accessor(area_, storageCache_, GetMetricsRegistry());
-        accessor.Read(dicom, attachment);
+        DicomDataSource::Dicom::Lock lock(*dicom);
+        OrthancConfiguration::DefaultDicomDatasetToJson(result, lock.GetContent(), ignoreTagLength);
       }
 
-      ParsedDicomFile parsed(dicom);
-      OrthancConfiguration::DefaultDicomDatasetToJson(result, parsed, ignoreTagLength);
       InjectEmptyPixelData(result);
     }
     else
@@ -1309,17 +1348,15 @@
          * this case cannot be used if "StorageCompression" option is
          * "true".
          **/
-      
-        std::string dicom;
-        
+
+        std::unique_ptr<DicomDataSource::Dicom> dicom(
+          DicomDataSource::ReadUntilPixelData(*dicomReader_, attachment, pixelDataOffset));
+
         {
-          StorageAccessor accessor(area_, storageCache_, GetMetricsRegistry());
-          accessor.ReadStartRange(dicom, attachment, pixelDataOffset);
+          DicomDataSource::Dicom::Lock lock(*dicom);
+          OrthancConfiguration::DefaultDicomDatasetToJson(result, lock.GetContent(), ignoreTagLength);
         }
         
-        assert(dicom.size() == pixelDataOffset);
-        ParsedDicomFile parsed(dicom);
-        OrthancConfiguration::DefaultDicomDatasetToJson(result, parsed, ignoreTagLength);
         InjectEmptyPixelData(result);
       }
       else if (ignoreTagLength.empty() &&
@@ -1332,15 +1369,12 @@
          * "/tools/invalidate-tags" or to one flavors of
          * "/.../.../reconstruct" will disable this case.
          **/
-      
-        std::string dicomAsJson;
 
-        {
-          StorageAccessor accessor(area_, storageCache_, GetMetricsRegistry());
-          accessor.Read(dicomAsJson, attachment);
-        }
+        std::unique_ptr<StorageAreaDataSource::Range> dicomAsJson(
+          StorageAreaDataSource::ReadAttachment(
+            *storageAreaReader_, attachment, true /* uncompress */, checkMD5_));
 
-        if (!Toolbox::ReadJson(result, dicomAsJson))
+        if (!Toolbox::ReadJson(result, dicomAsJson->GetData(), dicomAsJson->GetSize()))
         {
           throw OrthancException(ErrorCode_CorruptedFile,
                                  "Corrupted DICOM-as-JSON attachment of instance: " + instancePublicId);
@@ -1354,36 +1388,45 @@
          * file from the storage area.
          **/
 
-        std::string dicom;
-        ReadDicom(dicom, instancePublicId);
+        if (!LookupAttachment(attachment, FileContentType_Dicom, instanceAttachments))
+        {
+          throw OrthancException(ErrorCode_UnknownResource);
+        }
 
-        ParsedDicomFile parsed(dicom);
-        OrthancConfiguration::DefaultDicomDatasetToJson(result, parsed, ignoreTagLength);
+        std::unique_ptr<DicomDataSource::Dicom> dicom(
+          DicomDataSource::ReadWhole(*dicomReader_, attachment, !hasPixelDataOffset /* raw buffer is needed for (*) */, checkMD5_));
 
-        if (!hasPixelDataOffset)
         {
-          /**
-           * The pixel data offset was never computed for this
-           * instance, which indicates that it was created using
-           * Orthanc <= 1.9.0, or that calls to
-           * "LookupPixelDataOffset()" from earlier versions of
-           * Orthanc have failed. Try again this precomputation now
-           * for future calls.
-           **/
-          ValueRepresentation pixelDataVR;
-          if (DicomStreamReader::LookupPixelDataOffset(pixelDataOffset, pixelDataVR, dicom) &&
-              pixelDataOffset < dicom.size())
+          DicomDataSource::Dicom::Lock lock(*dicom);
+          OrthancConfiguration::DefaultDicomDatasetToJson(result, lock.GetContent(), ignoreTagLength);
+
+          if (!hasPixelDataOffset)
           {
-            index_.OverwriteMetadata(instancePublicId, MetadataType_Instance_PixelDataOffset,
-                                     boost::lexical_cast<std::string>(pixelDataOffset));
+            /**
+             * (*) The pixel data offset was never computed for this
+             * instance, which indicates that it was created using
+             * Orthanc <= 1.9.0, or that calls to
+             * "LookupPixelDataOffset()" from earlier versions of
+             * Orthanc have failed. Try again this precomputation now
+             * for future calls.
+             **/
 
-            if (!area_.HasEfficientReadRange() ||
-                compressionEnabled_)
+            ValueRepresentation pixelDataVR;
+            if (DicomStreamReader::LookupPixelDataOffset(
+                  pixelDataOffset, pixelDataVR, lock.GetRawBufferData(), lock.GetRawBufferSize()) &&
+                pixelDataOffset < lock.GetRawBufferSize())
             {
-              int64_t newRevision;
-              AddAttachment(newRevision, instancePublicId, ResourceType_Instance, FileContentType_DicomUntilPixelData,
-                            dicom.empty() ? NULL: dicom.c_str(), pixelDataOffset,
-                             false /* no old revision */, -1 /* dummy revision */, "" /* dummy MD5 */);
+              index_.OverwriteMetadata(instancePublicId, MetadataType_Instance_PixelDataOffset,
+                                       boost::lexical_cast<std::string>(pixelDataOffset));
+
+              if (!area_.HasEfficientReadRange() ||
+                  compressionEnabled_)
+              {
+                int64_t newRevision;
+                AddAttachment(newRevision, instancePublicId, ResourceType_Instance, FileContentType_DicomUntilPixelData,
+                              lock.GetRawBufferData(), pixelDataOffset,
+                              false /* no old revision */, -1 /* dummy revision */, "" /* dummy MD5 */);
+              }
             }
           }
         }
@@ -1404,16 +1447,6 @@
                                 std::string& attachmentId,
                                 const std::string& instancePublicId)
   {
-    std::unique_ptr<Semaphore::Locker> dummyLargeDicomLocker;  // only the DicomCacheLocker uses a real largeDicomLocker_
-    ReadDicomInternal(dicom, attachmentId, instancePublicId, dummyLargeDicomLocker, 0);
-  }
-
-  void ServerContext::ReadDicomInternal(std::string& dicom,
-                                        std::string& attachmentId,
-                                        const std::string& instancePublicId,
-                                        std::unique_ptr<Semaphore::Locker>& largeDicomLocker,
-                                        std::size_t largeDicomThreshold)
-  {
     FileInfo attachment;
     int64_t revision;
 
@@ -1427,15 +1460,14 @@
     assert(attachment.GetContentType() == FileContentType_Dicom);
     attachmentId = attachment.GetUuid();
 
-    if (attachment.GetUncompressedSize() < largeDicomThreshold)  // release ASAP (before the read) if we don't plan to hold the lock (https://discourse.orthanc-server.org/t/patch-release-large-dicom-semaphore-lock-early-for-better-performance/6440)
-    {
-      largeDicomLocker.reset(NULL);
-    }
+    std::unique_ptr<StorageAreaDataSource::Range> range(
+      StorageAreaDataSource::ReadAttachment(
+        *storageAreaReader_, attachment, true /* uncompress */, checkMD5_));
 
-    ReadAttachment(dicom, attachment, true /* uncompress */);
+    assert(range->GetSize() == attachment.GetUncompressedSize());
+    range->Copy(dicom);
   }
 
-
   void ServerContext::ReadDicom(std::string& dicom,
                                 const std::string& instancePublicId)
   {
@@ -1443,15 +1475,24 @@
     ReadDicom(dicom, attachmentId, instancePublicId);    
   }
 
-  void ServerContext::ReadDicomInternal(std::string& dicom,
-                                        const std::string& instancePublicId,
-                                        std::unique_ptr<Semaphore::Locker>& largeDicomLocker,
-                                        std::size_t largeDicomThreshold)
+
+  DicomDataSource::Dicom* ServerContext::ReadParsedDicom(const std::string& instancePublicId,
+                                                         bool keepRawBuffer)
   {
-    std::string attachmentId;
-    ReadDicomInternal(dicom, attachmentId, instancePublicId, largeDicomLocker, largeDicomThreshold);
+    FileInfo attachment;
+    int64_t revision;
+
+    if (!index_.LookupAttachment(attachment, revision, ResourceType_Instance, instancePublicId, FileContentType_Dicom))
+    {
+      throw OrthancException(ErrorCode_InternalError,
+                             "Unable to read attachment " + EnumerationToString(FileContentType_Dicom) +
+                             " of instance " + instancePublicId);
+    }
+
+    return DicomDataSource::ReadWhole(*dicomReader_, attachment, keepRawBuffer, checkMD5_);
   }
 
+
   void ServerContext::ReadDicomForHeader(std::string& dicom,
                                          const std::string& instancePublicId)
   {
@@ -1468,10 +1509,12 @@
     int64_t revision;  // Ignored
     if (index_.LookupAttachment(attachment, revision, ResourceType_Instance, instancePublicId, FileContentType_DicomUntilPixelData))
     {
-      StorageAccessor accessor(area_, storageCache_, GetMetricsRegistry());
+      std::unique_ptr<StorageAreaDataSource::Range> range(
+        StorageAreaDataSource::ReadAttachment(
+          *storageAreaReader_, attachment, true /* uncompress */, checkMD5_));
 
-      accessor.Read(dicom, attachment);
-      assert(dicom.size() == attachment.GetUncompressedSize());
+      assert(range->GetSize() == attachment.GetUncompressedSize());
+      range->Copy(dicom);
 
       return true;
     }
@@ -1498,11 +1541,12 @@
 
       if (SerializationToolbox::ParseUnsignedInteger64(pixelDataOffset, s))
       {
-        StorageAccessor accessor(area_, storageCache_, GetMetricsRegistry());
+        std::unique_ptr<StorageAreaDataSource::Range> range(
+          StorageAreaDataSource::ReadBeginning(*storageAreaReader_, attachment, pixelDataOffset));
 
-        accessor.ReadStartRange(dicom, attachment, pixelDataOffset);
-        assert(dicom.size() == pixelDataOffset);
-        
+        assert(range->GetSize() == pixelDataOffset);
+        range->Copy(dicom);
+
         return true;   // Success
       }
       else
@@ -1515,44 +1559,6 @@
   }
   
 
-  void ServerContext::ReadAttachment(std::string& result,
-                                     const FileInfo& attachment,
-                                     bool uncompressIfNeeded,
-                                     bool skipCache)
-  {
-    std::unique_ptr<StorageAccessor> accessor;
-      
-    if (skipCache)
-    {
-      accessor.reset(new StorageAccessor(area_, GetMetricsRegistry()));
-    }
-    else
-    {
-      accessor.reset(new StorageAccessor(area_, storageCache_, GetMetricsRegistry()));
-    }
-
-    if (uncompressIfNeeded)
-    {
-      accessor->Read(result, attachment);
-    }
-    else
-    {
-      // Do not uncompress the content of the storage area, return the
-      // raw data
-      accessor->ReadRaw(result, attachment);
-    }
-  }
-
-  void ServerContext::ReadAttachmentRange(std::string &result,
-                                          const FileInfo &attachment,
-                                          const StorageRange &range,
-                                          bool uncompressIfNeeded)
-  {
-    StorageAccessor accessor(area_, storageCache_, GetMetricsRegistry());
-    accessor.ReadRange(result, attachment, range, uncompressIfNeeded);
-  }
-
-
   ServerContext::DicomCacheLocker::DicomCacheLocker(ServerContext& context,
                                                     const std::string& instancePublicId) :
     context_(context),
@@ -1567,9 +1573,7 @@
       // Throttle to avoid loading several large DICOM files simultaneously (since the ParsedDicomCache is 128MB, loading multiple 50MB files would throw them out directly after loading)
       largeDicomLocker_.reset(new Semaphore::Locker(context.largeDicomThrottler_));
       
-      // Release the throttle if loading "small" DICOM files (under
-      // 50MB, which is an arbitrary value)
-      context_.ReadDicomInternal(buffer_, instancePublicId_, largeDicomLocker_, static_cast<size_t>(50) * 1024 * 1024);
+      context_.ReadDicom(buffer_, instancePublicId_);
       
       dicom_.reset(new ParsedDicomFile(buffer_));
       dicomSize_ = buffer_.size();
@@ -1925,14 +1929,17 @@
   }
 
 
-
-
-
   ImageAccessor* ServerContext::DecodeDicomFrame(const std::string& publicId,
                                                  unsigned int frameIndex)
   {
-    ServerContext::DicomCacheLocker locker(*this, publicId);
-    std::unique_ptr<ImageAccessor> decoded(DecodeDicomFrame(locker.GetDicom(), locker.GetBuffer().c_str(), locker.GetBuffer().size(), frameIndex));
+    std::unique_ptr<DicomDataSource::Dicom> dicom(ReadParsedDicom(publicId, true /* raw buffer is necessary for transcoding */));
+
+    std::unique_ptr<ImageAccessor> decoded;
+
+    {
+      DicomDataSource::Dicom::Lock lock(*dicom);
+      decoded.reset(DecodeDicomFrame(lock.GetContent(), lock.GetRawBufferData(), lock.GetRawBufferSize(), frameIndex));
+    }
 
     if (decoded.get() == NULL)
     {
@@ -1943,8 +1950,10 @@
       }
       return NULL;
     }
-
-    return decoded.release();
+    else
+    {
+      return decoded.release();
+    }
   }
 
 
--- a/OrthancServer/Sources/ServerContext.h	Tue May 19 12:56:29 2026 +0200
+++ b/OrthancServer/Sources/ServerContext.h	Tue May 19 14:00:46 2026 +0200
@@ -29,6 +29,8 @@
 #include "ServerIndex.h"
 #include "ServerJobs/IStorageCommitmentFactory.h"
 
+#include "../../OrthancFramework/Sources/DataSource/DataSourceReader.h"
+#include "../../OrthancFramework/Sources/DataSource/DicomDataSource.h"
 #include "../../OrthancFramework/Sources/DicomParsing/DicomModification.h"
 #include "../../OrthancFramework/Sources/DicomParsing/IDicomTranscoder.h"
 #include "../../OrthancFramework/Sources/DicomParsing/ParsedDicomCache.h"
@@ -287,6 +289,11 @@
 
     boost::posix_time::ptime serverStartTimeUtc_;
 
+    // For streaming
+    bool                                 checkMD5_;
+    boost::shared_ptr<DataSourceReader>  storageAreaReader_;
+    std::unique_ptr<DataSourceReader>    dicomReader_;
+
   public:
     class DicomCacheLocker : public boost::noncopyable
     {
@@ -398,19 +405,6 @@
     void ReadDicomAsJson(Json::Value& result,
                          const std::string& instancePublicId);  // TODO-FIND: Can this be removed?
 
-private:
-    void ReadDicomInternal(std::string& dicom,
-                           const std::string& instancePublicId,
-                           std::unique_ptr<Semaphore::Locker>& largeDicomLocker,
-                           std::size_t largeDicomThreshold);
-
-    void ReadDicomInternal(std::string& dicom,
-                           std::string& attachmentId,
-                           const std::string& instancePublicId,
-                           std::unique_ptr<Semaphore::Locker>& largeDicomLocker,
-                           std::size_t largeDicomThreshold);
-
-public:
     void ReadDicom(std::string& dicom,
                    const std::string& instancePublicId);
 
@@ -418,23 +412,15 @@
                    std::string& attachmentId,
                    const std::string& instancePublicId);
 
+    DicomDataSource::Dicom* ReadParsedDicom(const std::string& instancePublicId,
+                                            bool keepRawBuffer);
+
     void ReadDicomForHeader(std::string& dicom,
                             const std::string& instancePublicId);
 
     bool ReadDicomUntilPixelData(std::string& dicom,
                                  const std::string& instancePublicId);
 
-    // This method is for low-level operations on "/instances/.../attachments/..."
-    void ReadAttachment(std::string& result,
-                        const FileInfo& attachment,
-                        bool uncompressIfNeeded,
-                        bool skipCache = false);
-
-    void ReadAttachmentRange(std::string& result,
-                             const FileInfo& attachment,
-                             const StorageRange& range,
-                             bool uncompressIfNeeded);
-
     void SetStoreMD5ForAttachments(bool storeMD5);
 
     bool IsStoreMD5ForAttachments() const
@@ -655,5 +641,20 @@
     int64_t GetServerUpTime() const;
 
     void PublishCacheMetrics();
+
+    bool IsCheckMD5() const
+    {
+      return checkMD5_;
+    }
+
+    DataSourceReader& GetStorageAreaReader() const
+    {
+      return *storageAreaReader_;
+    }
+
+    DataSourceReader& GetDicomReader() const
+    {
+      return *dicomReader_;
+    }
   };
 }
--- a/OrthancServer/Sources/ServerJobs/ThreadedInstancesLoader.cpp	Tue May 19 12:56:29 2026 +0200
+++ b/OrthancServer/Sources/ServerJobs/ThreadedInstancesLoader.cpp	Tue May 19 14:00:46 2026 +0200
@@ -22,10 +22,11 @@
 
 #include "ThreadedInstancesLoader.h"
 
-#include "../ServerContext.h"
+#include "../../../OrthancFramework/Sources/DataSource/StorageAreaDataSource.h"
+#include "../../../OrthancFramework/Sources/DicomParsing/FromDcmtkBridge.h"
+#include "../../../OrthancFramework/Sources/DicomParsing/IDicomTranscoder.h"
 #include "../../../OrthancFramework/Sources/Logging.h"
-#include "../../../OrthancFramework/Sources/DicomParsing/IDicomTranscoder.h"
-#include "../../../OrthancFramework/Sources/DicomParsing/FromDcmtkBridge.h"
+#include "../ServerContext.h"
 
 static boost::mutex loaderThreadsCounterMutex;
 static uint32_t loaderThreadsCounter = 0;
@@ -176,7 +177,14 @@
       try
       {
         boost::shared_ptr<std::string> dicomContent(new std::string());
-        that->context_.ReadAttachment(*dicomContent, instanceToPreload->GetFileInfo(), true);
+
+        {
+          std::unique_ptr<StorageAreaDataSource::Range> tmp(
+            StorageAreaDataSource::ReadAttachment(
+              that->context_.GetStorageAreaReader(), instanceToPreload->GetFileInfo(),
+              true /* uncompress */, that->context_.IsCheckMD5()));
+          tmp->Copy(*dicomContent);
+        }
 
         if (that->transcode_)
         {