changeset 6811:9b416c2b0471 streaming

integration mainline->streaming
author Sebastien Jodogne <s.jodogne@gmail.com>
date Tue, 19 May 2026 15:14:48 +0200
parents 3f5309b92016 (current diff) 65060f296783 (diff)
children d689c2f52405
files OrthancServer/Sources/OrthancRestApi/OrthancRestResources.cpp OrthancServer/Sources/ServerContext.cpp OrthancServer/Sources/ServerContext.h OrthancServer/Sources/ServerJobs/ThreadedInstancesLoader.cpp
diffstat 16 files changed, 377 insertions(+), 203 deletions(-) [+]
line wrap: on
line diff
--- a/OrthancServer/CMakeLists.txt	Tue May 19 14:00:46 2026 +0200
+++ b/OrthancServer/CMakeLists.txt	Tue May 19 15:14:48 2026 +0200
@@ -166,6 +166,7 @@
   ${CMAKE_SOURCE_DIR}/Sources/ServerJobs/ThreadedInstancesLoader.cpp
   ${CMAKE_SOURCE_DIR}/Sources/ServerJobs/ThreadedSetOfInstancesJob.cpp  
   ${CMAKE_SOURCE_DIR}/Sources/ServerToolbox.cpp
+  ${CMAKE_SOURCE_DIR}/Sources/ServerTranscoder.cpp
   ${CMAKE_SOURCE_DIR}/Sources/SimpleInstanceOrdering.cpp
   ${CMAKE_SOURCE_DIR}/Sources/SliceOrdering.cpp
   ${CMAKE_SOURCE_DIR}/Sources/StorageCommitmentReports.cpp
--- a/OrthancServer/Plugins/Engine/OrthancPlugins.cpp	Tue May 19 14:00:46 2026 +0200
+++ b/OrthancServer/Plugins/Engine/OrthancPlugins.cpp	Tue May 19 15:14:48 2026 +0200
@@ -6081,7 +6081,7 @@
 
           {
             PImpl::ServerContextReference lock(*pimpl_);
-            success = lock.GetContext().Transcode(transcoded, source, syntaxes, TranscodingSopInstanceUidMode_AllowNew);
+            success = lock.GetContext().GetTranscoder().Transcode(transcoded, source, syntaxes, TranscodingSopInstanceUidMode_AllowNew);
           }
 
           if (success)
--- a/OrthancServer/Sources/OrthancGetRequestHandler.cpp	Tue May 19 14:00:46 2026 +0200
+++ b/OrthancServer/Sources/OrthancGetRequestHandler.cpp	Tue May 19 15:14:48 2026 +0200
@@ -331,7 +331,7 @@
       std::set<DicomTransferSyntax> ts;
       ts.insert(selectedSyntax);
       
-      if (context_.Transcode(transcoded, source, ts, TranscodingSopInstanceUidMode_AllowNew))
+      if (context_.GetTranscoder().Transcode(transcoded, source, ts, TranscodingSopInstanceUidMode_AllowNew))
       {
         // Transcoding has succeeded
         DcmDataset *stDetailTmp = NULL;
--- a/OrthancServer/Sources/OrthancRestApi/OrthancRestAnonymizeModify.cpp	Tue May 19 14:00:46 2026 +0200
+++ b/OrthancServer/Sources/OrthancRestApi/OrthancRestAnonymizeModify.cpp	Tue May 19 15:14:48 2026 +0200
@@ -233,7 +233,7 @@
       std::set<DicomTransferSyntax> s;
       s.insert(targetSyntax);
       
-      if (context.Transcode(transcoded, source, s, TranscodingSopInstanceUidMode_AllowNew, lossyQuality))
+      if (context.GetTranscoder().Transcode(transcoded, source, s, TranscodingSopInstanceUidMode_AllowNew, lossyQuality))
       {      
         call.GetOutput().AnswerBuffer(transcoded.GetBufferData(),
                                       transcoded.GetBufferSize(), MimeType_Dicom);
--- a/OrthancServer/Sources/OrthancRestApi/OrthancRestResources.cpp	Tue May 19 14:00:46 2026 +0200
+++ b/OrthancServer/Sources/OrthancRestApi/OrthancRestResources.cpp	Tue May 19 15:14:48 2026 +0200
@@ -432,7 +432,7 @@
         std::set<DicomTransferSyntax> allowedSyntaxes;
         allowedSyntaxes.insert(GetTransferSyntax(call.GetArgument(GET_TRANSCODE, "")));
 
-        if (context.Transcode(targetImage, sourceImage, allowedSyntaxes, TranscodingSopInstanceUidMode_AllowNew, lossyQuality))
+        if (context.GetTranscoder().Transcode(targetImage, sourceImage, allowedSyntaxes, TranscodingSopInstanceUidMode_AllowNew, lossyQuality))
         {
           call.GetOutput().SetContentFilename(filename.c_str());
           call.GetOutput().AnswerBuffer(targetImage.GetBufferData(), targetImage.GetBufferSize(), MimeType_Dicom);
--- a/OrthancServer/Sources/ServerContext.cpp	Tue May 19 14:00:46 2026 +0200
+++ b/OrthancServer/Sources/ServerContext.cpp	Tue May 19 15:14:48 2026 +0200
@@ -29,10 +29,8 @@
 #include "../../OrthancFramework/Sources/DicomFormat/DicomElement.h"
 #include "../../OrthancFramework/Sources/DicomFormat/DicomStreamReader.h"
 #include "../../OrthancFramework/Sources/DicomNetworking/DicomStoreUserConnection.h"
-#include "../../OrthancFramework/Sources/DicomParsing/DcmtkTranscoder.h"
 #include "../../OrthancFramework/Sources/DicomParsing/DicomModification.h"
 #include "../../OrthancFramework/Sources/DicomParsing/FromDcmtkBridge.h"
-#include "../../OrthancFramework/Sources/DicomParsing/Internals/DicomImageDecoder.h"
 #include "../../OrthancFramework/Sources/FileStorage/StorageAccessor.h"
 #include "../../OrthancFramework/Sources/HttpServer/FilesystemHttpSender.h"
 #include "../../OrthancFramework/Sources/HttpServer/HttpStreamTranscoder.h"
@@ -377,8 +375,7 @@
                                IPluginStorageArea& area,
                                bool unitTesting,
                                size_t maxCompletedJobs,
-                               bool readOnly,
-                               unsigned int maxConcurrentDcmtkTranscoder) :
+                               bool readOnly) :
     index_(*this, database, (unitTesting ? 20 : 500), readOnly),
     area_(area),
     compressionEnabled_(false),
@@ -400,7 +397,6 @@
     isExecuteLuaEnabled_(false),
     isRestApiWriteToFileSystemEnabled_(false),
     overwriteInstances_(OverwriteInstancesMode_Never),
-    dcmtkTranscoder_(new DcmtkTranscoder(maxConcurrentDcmtkTranscoder)),
     isIngestTranscoding_(false),
     ingestTranscodingOfUncompressed_(true),
     ingestTranscodingOfCompressed_(true),
@@ -442,7 +438,6 @@
 
         // New options in Orthanc 1.7.0
         transcodeDicomProtocol_ = lock.GetConfiguration().GetBooleanParameter("TranscodeDicomProtocol", true);
-        builtinDecoderTranscoderOrder_ = StringToBuiltinDecoderTranscoderOrder(lock.GetConfiguration().GetStringParameter("BuiltinDecoderTranscoderOrder", "After"));
 
         std::string s;
         if (lock.GetConfiguration().LookupStringParameter(s, ORTHANC_CONFIG_INGEST_TRANSCODING))
@@ -540,8 +535,6 @@
 
         defaultDicomRetrieveMethod_ = StringToRetrieveMethod(lock.GetConfiguration().GetDicomDefaultRetrieveMethod());
 
-        dynamic_cast<DcmtkTranscoder&>(*dcmtkTranscoder_).SetDefaultLossyQuality(lock.GetConfiguration().GetDicomLossyTranscodingQuality());
-
         checkMD5_ = lock.GetConfiguration().GetBooleanParameter("CheckMD5", true);  // TODO-Streaming - Parameter
       }
 
@@ -1088,7 +1081,7 @@
         
         IDicomTranscoder::DicomImage transcoded;
         
-        if (Transcode(transcoded, source, syntaxes, TranscodingSopInstanceUidMode_AllowNew /* allow new SOP instance UID */))
+        if (GetTranscoder().Transcode(transcoded, source, syntaxes, TranscodingSopInstanceUidMode_AllowNew /* allow new SOP instance UID */))
         {
           std::unique_ptr<ParsedDicomFile> tmp(transcoded.ReleaseAsParsedDicomFile());
 
@@ -1938,7 +1931,7 @@
 
     {
       DicomDataSource::Dicom::Lock lock(*dicom);
-      decoded.reset(DecodeDicomFrame(lock.GetContent(), lock.GetRawBufferData(), lock.GetRawBufferSize(), frameIndex));
+      decoded.reset(GetTranscoder().DecodeFrame(lock.GetContent(), lock.GetRawBufferData(), lock.GetRawBufferSize(), frameIndex));
     }
 
     if (decoded.get() == NULL)
@@ -1957,101 +1950,13 @@
   }
 
 
-  ImageAccessor* ServerContext::DecodeDicomFrame(const ParsedDicomFile& parsedDicom,
-                                                 const void* buffer,  // actually the buffer that is the source of the ParsedDicomFile
-                                                 size_t size,
-                                                 unsigned int frameIndex)
-  {
-    std::unique_ptr<ImageAccessor> decoded;
-
-    if (builtinDecoderTranscoderOrder_ == BuiltinDecoderTranscoderOrder_Before)
-    {
-      // Use Orthanc's built-in decoder
-
-      try
-      {
-        decoded.reset(parsedDicom.DecodeFrame(frameIndex));
-        if (decoded.get() != NULL)
-        {
-          return decoded.release();
-        }
-      }
-      catch (const OrthancException&) // NOLINT(bugprone-empty-catch)
-      { // ignore, we'll try other alternatives
-      }
-    }
-
-#if ORTHANC_ENABLE_PLUGINS == 1
-    if (HasPlugins() &&
-        GetPlugins().HasCustomImageDecoder())
-    {
-      try
-      {
-        decoded.reset(GetPlugins().Decode(buffer, size, frameIndex));
-      }
-      catch (const OrthancException&) // NOLINT(bugprone-empty-catch)
-      {
-      }
-      
-      if (decoded.get() != NULL)
-      {
-        return decoded.release();
-      }
-      else if (builtinDecoderTranscoderOrder_ == BuiltinDecoderTranscoderOrder_After)
-      {
-        LOG(INFO) << "The installed image decoding plugins cannot handle an image, "
-                  << "fallback to the built-in DCMTK decoder";
-      }
-    }
-#endif
-
-    if (builtinDecoderTranscoderOrder_ == BuiltinDecoderTranscoderOrder_After)
-    {
-      try
-      { 
-        decoded.reset(parsedDicom.DecodeFrame(frameIndex));
-        if (decoded.get() != NULL)
-        {
-          return decoded.release();
-        }
-      }
-      catch (OrthancException& e)
-      {
-        LOG(INFO) << "Failed to decode a DICOM frame: " << e.GetDetails();
-      }
-    }
-
-#if ORTHANC_ENABLE_PLUGINS == 1
-    if (HasPlugins() && GetPlugins().HasCustomTranscoder())
-    {
-      LOG(INFO) << "The plugins and built-in image decoders failed to decode a frame, "
-                << "trying to transcode the file to LittleEndianExplicit using the plugins.";
-      DicomImage explicitTemporaryImage;
-      DicomImage source;
-      std::set<DicomTransferSyntax> allowedSyntaxes;
-
-      source.SetExternalBuffer(buffer, size);
-      allowedSyntaxes.insert(DicomTransferSyntax_LittleEndianExplicit);
-
-      if (Transcode(explicitTemporaryImage, source, allowedSyntaxes, TranscodingSopInstanceUidMode_AllowNew))
-      {
-        std::unique_ptr<ParsedDicomFile> file(explicitTemporaryImage.ReleaseAsParsedDicomFile());
-        return file->DecodeFrame(frameIndex);
-      }
-    }
-#endif
-
-    return NULL;
-  }
-
-
   ImageAccessor* ServerContext::DecodeDicomFrame(const DicomInstanceToStore& dicom,
                                                  unsigned int frameIndex)
   {
-    return DecodeDicomFrame(dicom.GetParsedDicomFile(),
-                            dicom.GetBufferData(),
-                            dicom.GetBufferSize(),
-                            frameIndex);
+    return GetTranscoder().DecodeFrame(dicom.GetParsedDicomFile(),
+                                    dicom.GetBufferData(),
+                                    dicom.GetBufferSize(),
+                                    frameIndex);
 
   }
 
@@ -2061,7 +1966,7 @@
                                                  unsigned int frameIndex)
   {
     std::unique_ptr<ParsedDicomFile> instance(new ParsedDicomFile(dicom, size));
-    return DecodeDicomFrame(*instance, dicom, size, frameIndex);
+    return GetTranscoder().DecodeFrame(*instance, dicom, size, frameIndex);
   }
   
 
@@ -2114,7 +2019,7 @@
     }
     else
     {
-      connection.Transcode(sopClassUid, sopInstanceUid, *this, data, dicom.size(), preferredTransferSyntax_,
+      connection.Transcode(sopClassUid, sopInstanceUid, *transcoder_, data, dicom.size(), preferredTransferSyntax_,
                            hasMoveOriginator, moveOriginatorAet, moveOriginatorId);
     }
   }
@@ -2137,7 +2042,7 @@
       std::set<DicomTransferSyntax> syntaxes;
       syntaxes.insert(targetSyntax);
 
-      if (Transcode(targetDicom, sourceDicom, syntaxes, TranscodingSopInstanceUidMode_AllowNew))
+      if (GetTranscoder().Transcode(targetDicom, sourceDicom, syntaxes, TranscodingSopInstanceUidMode_AllowNew))
       {
         cacheAccessor.AddTranscodedInstance(attachmentId, targetSyntax, reinterpret_cast<const char*>(targetDicom.GetBufferData()), targetDicom.GetBufferSize());
         target = std::string(reinterpret_cast<const char*>(targetDicom.GetBufferData()), targetDicom.GetBufferSize());
@@ -2150,62 +2055,6 @@
     return true;
   }
 
-  bool ServerContext::Transcode(DicomImage& target,
-                                DicomImage& source /* in, "GetParsed()" possibly modified */,
-                                const std::set<DicomTransferSyntax>& allowedSyntaxes,
-                                TranscodingSopInstanceUidMode mode)
-  {
-    unsigned int lossyQuality;
-
-    {
-      OrthancConfiguration::ReaderLock lock;
-      lossyQuality = lock.GetConfiguration().GetDicomLossyTranscodingQuality();
-    }
-
-    return Transcode(target, source, allowedSyntaxes, mode, lossyQuality);
-  }
-
-
-  bool ServerContext::Transcode(DicomImage& target,
-                                DicomImage& source /* in, "GetParsed()" possibly modified */,
-                                const std::set<DicomTransferSyntax>& allowedSyntaxes,
-                                TranscodingSopInstanceUidMode mode,
-                                unsigned int lossyQuality)
-  {
-    if (builtinDecoderTranscoderOrder_ == BuiltinDecoderTranscoderOrder_Before)
-    {
-      if (dcmtkTranscoder_->Transcode(target, source, allowedSyntaxes, mode, lossyQuality))
-      {
-        return true;
-      }
-    }
-      
-#if ORTHANC_ENABLE_PLUGINS == 1
-    if (HasPlugins() &&
-        GetPlugins().HasCustomTranscoder())
-    {
-      if (GetPlugins().Transcode(target, source, allowedSyntaxes, mode))  // TODO: pass lossyQuality to plugins -> needs a new plugin interface
-      {
-        return true;
-      }
-      else if (builtinDecoderTranscoderOrder_ == BuiltinDecoderTranscoderOrder_After)
-      {
-        LOG(INFO) << "The installed transcoding plugins cannot handle an image, "
-                  << "fallback to the built-in DCMTK transcoder";
-      }
-    }
-#endif
-
-    if (builtinDecoderTranscoderOrder_ == BuiltinDecoderTranscoderOrder_After)
-    {
-      return dcmtkTranscoder_->Transcode(target, source, allowedSyntaxes, mode, lossyQuality);
-    }
-    else
-    {
-      return false;
-    }
-  }
-
 
   const std::string& ServerContext::GetDeidentifiedContent(const DicomElement &element) const
   {
@@ -2393,4 +2242,49 @@
 
     return elapsed.total_seconds();
   }
+
+
+  void ServerContext::SetTranscoder(ServerTranscoder* transcoder)
+  {
+    std::unique_ptr<ServerTranscoder> protection(transcoder);
+
+    if (transcoder == NULL)
+    {
+      throw OrthancException(ErrorCode_NullPointer);
+    }
+    else if (transcoder_.get() != NULL)
+    {
+      throw OrthancException(ErrorCode_BadSequenceOfCalls);
+    }
+    else
+    {
+      transcoder_.reset(protection.release());
+    }
+  }
+
+
+  ServerTranscoder& ServerContext::GetTranscoder() const
+  {
+    if (transcoder_.get() != NULL)
+    {
+      return *transcoder_;
+    }
+    else
+    {
+      throw OrthancException(ErrorCode_BadSequenceOfCalls);
+    }
+  }
+
+
+  void ServerContext::ResetTranscoder()
+  {
+    if (transcoder_.get() == NULL)
+    {
+      throw OrthancException(ErrorCode_BadSequenceOfCalls);
+    }
+    else
+    {
+      transcoder_.reset(NULL);
+    }
+  }
 }
--- a/OrthancServer/Sources/ServerContext.h	Tue May 19 14:00:46 2026 +0200
+++ b/OrthancServer/Sources/ServerContext.h	Tue May 19 15:14:48 2026 +0200
@@ -28,11 +28,11 @@
 #include "OrthancHttpHandler.h"
 #include "ServerIndex.h"
 #include "ServerJobs/IStorageCommitmentFactory.h"
+#include "ServerTranscoder.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"
 #include "../../OrthancFramework/Sources/FileStorage/StorageAccessor.h"
 #include "../../OrthancFramework/Sources/FileStorage/StorageCache.h"
@@ -56,7 +56,6 @@
    **/
   class ServerContext :
     public IStorageCommitmentFactory,
-    public IDicomTranscoder,
     private JobsRegistry::IObserver
   {
     friend class ServerIndex;  // To access "RemoveFile()"
@@ -249,9 +248,8 @@
 
     std::unique_ptr<StorageCommitmentReports>  storageCommitmentReports_;
 
+    std::unique_ptr<ServerTranscoder> transcoder_;
     bool transcodeDicomProtocol_;
-    std::unique_ptr<IDicomTranscoder>  dcmtkTranscoder_;
-    BuiltinDecoderTranscoderOrder builtinDecoderTranscoderOrder_;
     bool isIngestTranscoding_;
     DicomTransferSyntax ingestTransferSyntax_;
     bool ingestTranscodingOfUncompressed_;
@@ -321,8 +319,7 @@
                   IPluginStorageArea& area,
                   bool unitTesting,
                   size_t maxCompletedJobs,
-                  bool readOnly,
-                  unsigned int maxConcurrentDcmtkTranscoder);
+                  bool readOnly);
 
     ~ServerContext() ORTHANC_OVERRIDE;
 
@@ -579,11 +576,6 @@
                                     size_t size,
                                     unsigned int frameIndex);
 
-    ImageAccessor* DecodeDicomFrame(const ParsedDicomFile& parsedDicom,
-                                    const void* buffer,  // actually the buffer that is the source of the ParsedDicomFile
-                                    size_t size,
-                                    unsigned int frameIndex);
-
     void PerformCStoreWithTranscoding(std::string& sopClassUid,
                                       std::string& sopInstanceUid,
                                       DicomStoreUserConnection& connection,
@@ -592,19 +584,6 @@
                                       const std::string& moveOriginatorAet,
                                       uint16_t moveOriginatorId);
 
-    // This method can be used even if the global option
-    // "TranscodeDicomProtocol" is set to "false"
-    virtual bool Transcode(DicomImage& target,
-                           DicomImage& source /* in, "GetParsed()" possibly modified */,
-                           const std::set<DicomTransferSyntax>& allowedSyntaxes,
-                           TranscodingSopInstanceUidMode mode) ORTHANC_OVERRIDE;
-
-    virtual bool Transcode(DicomImage& target,
-                           DicomImage& source /* in, "GetParsed()" possibly modified */,
-                           const std::set<DicomTransferSyntax>& allowedSyntaxes,
-                           TranscodingSopInstanceUidMode mode,
-                           unsigned int lossyQuality) ORTHANC_OVERRIDE;
-
     virtual bool TranscodeWithCache(std::string& target,
                                     const std::string& source,
                                     const std::string& sourceInstanceId,
@@ -642,6 +621,12 @@
 
     void PublishCacheMetrics();
 
+    void SetTranscoder(ServerTranscoder* transcoder /* takes ownership */);
+
+    ServerTranscoder& GetTranscoder() const;
+
+    void ResetTranscoder();
+
     bool IsCheckMD5() const
     {
       return checkMD5_;
--- a/OrthancServer/Sources/ServerJobs/OrthancPeerStoreJob.cpp	Tue May 19 14:00:46 2026 +0200
+++ b/OrthancServer/Sources/ServerJobs/OrthancPeerStoreJob.cpp	Tue May 19 15:14:48 2026 +0200
@@ -72,7 +72,7 @@
         IDicomTranscoder::DicomImage source, transcoded;
         source.SetExternalBuffer(dicom);
 
-        if (context_.Transcode(transcoded, source, syntaxes, TranscodingSopInstanceUidMode_AllowNew))
+        if (context_.GetTranscoder().Transcode(transcoded, source, syntaxes, TranscodingSopInstanceUidMode_AllowNew))
         {
           body.assign(reinterpret_cast<const char*>(transcoded.GetBufferData()),
                       transcoded.GetBufferSize());
--- a/OrthancServer/Sources/ServerJobs/ResourceModificationJob.cpp	Tue May 19 14:00:46 2026 +0200
+++ b/OrthancServer/Sources/ServerJobs/ResourceModificationJob.cpp	Tue May 19 15:14:48 2026 +0200
@@ -262,7 +262,7 @@
       source.AcquireParsed(*modified);  // "modified" is invalid below this point
       
       IDicomTranscoder::DicomImage transcoded;
-      if (GetContext().Transcode(transcoded, source, syntaxes, TranscodingSopInstanceUidMode_AllowNew))
+      if (GetContext().GetTranscoder().Transcode(transcoded, source, syntaxes, TranscodingSopInstanceUidMode_AllowNew))
       {
         modified.reset(transcoded.ReleaseAsParsedDicomFile());
 
--- a/OrthancServer/Sources/ServerJobs/ThreadedInstancesLoader.cpp	Tue May 19 14:00:46 2026 +0200
+++ b/OrthancServer/Sources/ServerJobs/ThreadedInstancesLoader.cpp	Tue May 19 15:14:48 2026 +0200
@@ -267,7 +267,7 @@
       IDicomTranscoder::DicomImage source, transcoded;
       source.SetExternalBuffer(sourceBuffer);
 
-      if (context_.Transcode(transcoded, source, syntaxes, TranscodingSopInstanceUidMode_AllowNew, lossyQuality_))
+      if (context_.GetTranscoder().Transcode(transcoded, source, syntaxes, TranscodingSopInstanceUidMode_AllowNew, lossyQuality_))
       {
         transcodedBuffer.assign(reinterpret_cast<const char*>(transcoded.GetBufferData()), transcoded.GetBufferSize());
         return true;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/OrthancServer/Sources/ServerTranscoder.cpp	Tue May 19 15:14:48 2026 +0200
@@ -0,0 +1,214 @@
+/**
+ * Orthanc - A Lightweight, RESTful DICOM Store
+ * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics
+ * Department, University Hospital of Liege, Belgium
+ * Copyright (C) 2017-2023 Osimis S.A., Belgium
+ * Copyright (C) 2024-2026 Orthanc Team SRL, Belgium
+ * Copyright (C) 2021-2026 Sebastien Jodogne, ICTEAM UCLouvain, Belgium
+ *
+ * This program is free software: you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ * 
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ **/
+
+
+#include "PrecompiledHeadersServer.h"
+#include "ServerTranscoder.h"
+
+#include "../../OrthancFramework/Sources/DicomParsing/DcmtkTranscoder.h"
+#include "../../OrthancFramework/Sources/Logging.h"
+#include "../../OrthancFramework/Sources/OrthancException.h"
+#include "../Plugins/Engine/OrthancPlugins.h"
+#include "OrthancConfiguration.h"
+
+#include <dcmtk/dcmdata/dcfilefo.h>
+
+
+namespace Orthanc
+{
+  ServerTranscoder::ServerTranscoder(unsigned int maxConcurrentDcmtkTranscoder) :
+#if ORTHANC_ENABLE_PLUGINS == 1
+    plugins_(NULL),
+#endif
+    dcmtkTranscoder_(new DcmtkTranscoder(maxConcurrentDcmtkTranscoder)),
+    builtinDecoderTranscoderOrder_(BuiltinDecoderTranscoderOrder_After)
+  {
+    OrthancConfiguration::ReaderLock lock;
+
+    // New option in Orthanc 1.7.0
+    builtinDecoderTranscoderOrder_ = StringToBuiltinDecoderTranscoderOrder(lock.GetConfiguration().GetStringParameter("BuiltinDecoderTranscoderOrder", "After"));
+
+    // New option in Orthanc 1.12.6
+    dynamic_cast<DcmtkTranscoder&>(*dcmtkTranscoder_).SetDefaultLossyQuality(lock.GetConfiguration().GetDicomLossyTranscodingQuality());
+  }
+
+
+#if ORTHANC_ENABLE_PLUGINS == 1
+  void ServerTranscoder::SetPlugins(OrthancPlugins& plugins)
+  {
+    if (plugins_ == NULL)
+    {
+      plugins_ = &plugins;
+    }
+    else
+    {
+      throw OrthancException(ErrorCode_BadSequenceOfCalls);
+    }
+  }
+#endif
+
+
+  ImageAccessor* ServerTranscoder::DecodeFrame(const ParsedDicomFile& parsedDicom,
+                                               const void* buffer,
+                                               size_t size,
+                                               unsigned int frameIndex)
+  {
+    std::unique_ptr<ImageAccessor> decoded;
+
+    if (builtinDecoderTranscoderOrder_ == BuiltinDecoderTranscoderOrder_Before)
+    {
+      // Use Orthanc's built-in decoder
+
+      try
+      {
+        decoded.reset(parsedDicom.DecodeFrame(frameIndex));
+        if (decoded.get() != NULL)
+        {
+          return decoded.release();
+        }
+      }
+      catch (const OrthancException&) // NOLINT(bugprone-empty-catch)
+      { // ignore, we'll try other alternatives
+      }
+    }
+
+#if ORTHANC_ENABLE_PLUGINS == 1
+    if (plugins_ != NULL &&
+        plugins_->HasCustomImageDecoder())
+    {
+      try
+      {
+        decoded.reset(plugins_->Decode(buffer, size, frameIndex));
+      }
+      catch (const OrthancException&) // NOLINT(bugprone-empty-catch)
+      {
+      }
+
+      if (decoded.get() != NULL)
+      {
+        return decoded.release();
+      }
+      else if (builtinDecoderTranscoderOrder_ == BuiltinDecoderTranscoderOrder_After)
+      {
+        LOG(INFO) << "The installed image decoding plugins cannot handle an image, "
+                  << "fallback to the built-in DCMTK decoder";
+      }
+    }
+#endif
+
+    if (builtinDecoderTranscoderOrder_ == BuiltinDecoderTranscoderOrder_After)
+    {
+      try
+      {
+        decoded.reset(parsedDicom.DecodeFrame(frameIndex));
+        if (decoded.get() != NULL)
+        {
+          return decoded.release();
+        }
+      }
+      catch (OrthancException& e)
+      {
+        LOG(INFO) << "Failed to decode a DICOM frame: " << e.GetDetails();
+      }
+    }
+
+#if ORTHANC_ENABLE_PLUGINS == 1
+    if (plugins_ != NULL &&
+        plugins_->HasCustomTranscoder())
+    {
+      LOG(INFO) << "The plugins and built-in image decoders failed to decode a frame, "
+                << "trying to transcode the file to LittleEndianExplicit using the plugins.";
+      DicomImage explicitTemporaryImage;
+      DicomImage source;
+      std::set<DicomTransferSyntax> allowedSyntaxes;
+
+      source.SetExternalBuffer(buffer, size);
+      allowedSyntaxes.insert(DicomTransferSyntax_LittleEndianExplicit);
+
+      if (Transcode(explicitTemporaryImage, source, allowedSyntaxes, TranscodingSopInstanceUidMode_AllowNew))
+      {
+        std::unique_ptr<ParsedDicomFile> file(explicitTemporaryImage.ReleaseAsParsedDicomFile());
+        return file->DecodeFrame(frameIndex);
+      }
+    }
+#endif
+
+    return NULL;  // TODO-Streaming - Throw exception here?
+  }
+
+
+  bool ServerTranscoder::Transcode(DicomImage& target,
+                                   DicomImage& source,
+                                   const std::set<DicomTransferSyntax>& allowedSyntaxes,
+                                   TranscodingSopInstanceUidMode mode)
+  {
+    unsigned int lossyQuality;
+
+    {
+      OrthancConfiguration::ReaderLock lock;
+      lossyQuality = lock.GetConfiguration().GetDicomLossyTranscodingQuality();
+    }
+
+    return Transcode(target, source, allowedSyntaxes, mode, lossyQuality);
+  }
+
+
+  bool ServerTranscoder::Transcode(DicomImage& target,
+                                   DicomImage& source,
+                                   const std::set<DicomTransferSyntax>& allowedSyntaxes,
+                                   TranscodingSopInstanceUidMode mode,
+                                   unsigned int lossyQuality)
+  {
+    if (builtinDecoderTranscoderOrder_ == BuiltinDecoderTranscoderOrder_Before)
+    {
+      if (dcmtkTranscoder_->Transcode(target, source, allowedSyntaxes, mode, lossyQuality))
+      {
+        return true;
+      }
+    }
+
+#if ORTHANC_ENABLE_PLUGINS == 1
+    if (plugins_ != NULL &&
+        plugins_->HasCustomTranscoder())
+    {
+      if (plugins_->Transcode(target, source, allowedSyntaxes, mode))  // TODO: pass lossyQuality to plugins -> needs a new plugin interface
+      {
+        return true;
+      }
+      else if (builtinDecoderTranscoderOrder_ == BuiltinDecoderTranscoderOrder_After)
+      {
+        LOG(INFO) << "The installed transcoding plugins cannot handle an image, "
+                  << "fallback to the built-in DCMTK transcoder";
+      }
+    }
+#endif
+
+    if (builtinDecoderTranscoderOrder_ == BuiltinDecoderTranscoderOrder_After)
+    {
+      return dcmtkTranscoder_->Transcode(target, source, allowedSyntaxes, mode, lossyQuality);
+    }
+    else
+    {
+      return false;
+    }
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/OrthancServer/Sources/ServerTranscoder.h	Tue May 19 15:14:48 2026 +0200
@@ -0,0 +1,72 @@
+/**
+ * Orthanc - A Lightweight, RESTful DICOM Store
+ * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics
+ * Department, University Hospital of Liege, Belgium
+ * Copyright (C) 2017-2023 Osimis S.A., Belgium
+ * Copyright (C) 2024-2026 Orthanc Team SRL, Belgium
+ * Copyright (C) 2021-2026 Sebastien Jodogne, ICTEAM UCLouvain, Belgium
+ *
+ * This program is free software: you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ * 
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ **/
+
+
+#pragma once
+
+#include "../../OrthancFramework/Sources/DicomParsing/IDicomTranscoder.h"
+#include "../../OrthancFramework/Sources/Images/ImageAccessor.h"
+#include "ServerEnumerations.h"
+
+
+namespace Orthanc
+{
+#if ORTHANC_ENABLE_PLUGINS == 1
+  class OrthancPlugins;
+#endif
+
+  class ServerTranscoder : public IDicomTranscoder
+  {
+  private:
+#if ORTHANC_ENABLE_PLUGINS == 1
+    OrthancPlugins* plugins_;
+#endif
+
+    std::unique_ptr<IDicomTranscoder>  dcmtkTranscoder_;
+    BuiltinDecoderTranscoderOrder      builtinDecoderTranscoderOrder_;
+
+  public:
+    ServerTranscoder(unsigned int maxConcurrentDcmtkTranscoder);
+
+#if ORTHANC_ENABLE_PLUGINS == 1
+    void SetPlugins(OrthancPlugins& plugins);
+#endif
+
+    ImageAccessor* DecodeFrame(const ParsedDicomFile& parsedDicom,
+                               const void* buffer,  // buffer that is the source of the ParsedDicomFile
+                               size_t size,
+                               unsigned int frameIndex);
+
+    // This method can be used even if the global option
+    // "TranscodeDicomProtocol" is set to "false"
+    virtual bool Transcode(DicomImage& target,
+                           DicomImage& source /* in, "GetParsed()" possibly modified */,
+                           const std::set<DicomTransferSyntax>& allowedSyntaxes,
+                           TranscodingSopInstanceUidMode mode) ORTHANC_OVERRIDE;
+
+    virtual bool Transcode(DicomImage& target,
+                           DicomImage& source /* in, "GetParsed()" possibly modified */,
+                           const std::set<DicomTransferSyntax>& allowedSyntaxes,
+                           TranscodingSopInstanceUidMode mode,
+                           unsigned int lossyQuality)  ORTHANC_OVERRIDE;
+  };
+}
--- a/OrthancServer/Sources/main.cpp	Tue May 19 14:00:46 2026 +0200
+++ b/OrthancServer/Sources/main.cpp	Tue May 19 15:14:48 2026 +0200
@@ -1598,7 +1598,8 @@
 
   public:
     ServerContextConfigurator(ServerContext& context,
-                              OrthancPlugins* plugins) :
+                              OrthancPlugins* plugins,
+                              unsigned int maxDcmtkConcurrentTranscoders) :
       context_(context),
       plugins_(plugins)
     {
@@ -1607,14 +1608,19 @@
         lock.GetConfiguration().SetServerIndex(context.GetIndex());
       }
 
+      std::unique_ptr<ServerTranscoder> transcoder(new ServerTranscoder(maxDcmtkConcurrentTranscoders));
+
 #if ORTHANC_ENABLE_PLUGINS == 1
       if (plugins_ != NULL)
       {
         plugins_->SetServerContext(context_);
         context_.SetPlugins(*plugins_);
         context_.GetIndex().SetMaxDatabaseRetries(plugins_->GetMaxDatabaseRetries());
+        transcoder->SetPlugins(*plugins_);
       }
 #endif
+
+      context.SetTranscoder(transcoder.release());
     }
 
     ~ServerContextConfigurator()
@@ -1631,6 +1637,8 @@
         context_.ResetPlugins();
       }
 #endif
+
+      context_.ResetTranscoder();
     }
   };
 }
@@ -1702,7 +1710,7 @@
       lock.GetConfiguration().GetBooleanParameter(KEY_DICOM_TLS_REMOTE_CERTIFICATE_REQUIRED, true));
   }
   
-  ServerContext context(database, storageArea, false /* not running unit tests */, maxCompletedJobs, readOnly, maxDcmtkConcurrentTranscoders);
+  ServerContext context(database, storageArea, false /* not running unit tests */, maxCompletedJobs, readOnly);
 
   {
     OrthancConfiguration::ReaderLock lock;
@@ -1803,7 +1811,7 @@
   }
 
   {
-    ServerContextConfigurator configurator(context, plugins);  // This calls "OrthancConfiguration::SetServerIndex()"
+    ServerContextConfigurator configurator(context, plugins, maxDcmtkConcurrentTranscoders);  // This calls "OrthancConfiguration::SetServerIndex()"
 
     {
       OrthancConfiguration::WriterLock lock;
@@ -2172,7 +2180,7 @@
           SQLiteDatabaseWrapper inMemoryDatabase;
           inMemoryDatabase.Open();
           PluginStorageAreaAdapter inMemoryStorage(new MemoryStorageArea);
-          ServerContext context(inMemoryDatabase, inMemoryStorage, true /* unit testing */, 0 /* max completed jobs */, false /* readonly */, 1 /* DCMTK concurrent transcoders */);
+          ServerContext context(inMemoryDatabase, inMemoryStorage, true /* unit testing */, 0 /* max completed jobs */, false /* readonly */);
           OrthancRestApi restApi(context, false /* no Orthanc Explorer */);
           restApi.GenerateOpenApiDocumentation(openapi);
           context.Stop();
@@ -2223,7 +2231,7 @@
           SQLiteDatabaseWrapper inMemoryDatabase;
           inMemoryDatabase.Open();
           PluginStorageAreaAdapter inMemoryStorage(new MemoryStorageArea);
-          ServerContext context(inMemoryDatabase, inMemoryStorage, true /* unit testing */, 0 /* max completed jobs */, false /* readonly */, 1 /* DCMTK concurrent transcoders */);
+          ServerContext context(inMemoryDatabase, inMemoryStorage, true /* unit testing */, 0 /* max completed jobs */, false /* readonly */);
           OrthancRestApi restApi(context, false /* no Orthanc Explorer */);
           restApi.GenerateReStructuredTextCheatSheet(cheatsheet, "https://orthanc.uclouvain.be/api/index.html");
           context.Stop();
--- a/OrthancServer/UnitTestsSources/ServerConfigTests.cpp	Tue May 19 14:00:46 2026 +0200
+++ b/OrthancServer/UnitTestsSources/ServerConfigTests.cpp	Tue May 19 15:14:48 2026 +0200
@@ -39,7 +39,7 @@
   PluginStorageAreaAdapter storage(new MemoryStorageArea);
   SQLiteDatabaseWrapper db;   // The SQLite DB is in memory
   db.Open();
-  ServerContext context(db, storage, true /* running unit tests */, 10, false, 1);
+  ServerContext context(db, storage, true /* running unit tests */, 10, false);
 
   { // default config -> all SOP Classes should be accepted
     std::set<std::string> s;
--- a/OrthancServer/UnitTestsSources/ServerIndexTests.cpp	Tue May 19 14:00:46 2026 +0200
+++ b/OrthancServer/UnitTestsSources/ServerIndexTests.cpp	Tue May 19 15:14:48 2026 +0200
@@ -730,7 +730,7 @@
   PluginStorageAreaAdapter storage(new FilesystemStorage(path));
   SQLiteDatabaseWrapper db;   // The SQLite DB is in memory
   db.Open();
-  ServerContext context(db, storage, true /* running unit tests */, 10, false /* readonly */, 1 /* DCMTK concurrent transcoders */);
+  ServerContext context(db, storage, true /* running unit tests */, 10, false /* readonly */);
   context.SetupJobsEngine(true, false);
 
   ServerIndex& index = context.GetIndex();
@@ -812,7 +812,7 @@
   PluginStorageAreaAdapter storage(new FilesystemStorage(path));
   SQLiteDatabaseWrapper db;   // The SQLite DB is in memory
   db.Open();
-  ServerContext context(db, storage, true /* running unit tests */, 10, false /* readonly */, 1 /* DCMTK concurrent transcoders */);
+  ServerContext context(db, storage, true /* running unit tests */, 10, false /* readonly */);
   context.SetupJobsEngine(true, false);
   ServerIndex& index = context.GetIndex();
 
@@ -935,7 +935,7 @@
     PluginStorageAreaAdapter storage(new MemoryStorageArea);
     SQLiteDatabaseWrapper db;   // The SQLite DB is in memory
     db.Open();
-    ServerContext context(db, storage, true /* running unit tests */, 10, false /* readonly */, 1 /* DCMTK concurrent transcoders */);
+    ServerContext context(db, storage, true /* running unit tests */, 10, false /* readonly */);
     context.SetupJobsEngine(true, false);
     context.SetCompressionEnabled(true);
 
@@ -1100,7 +1100,7 @@
     PluginStorageAreaAdapter storage(new MemoryStorageArea);
     SQLiteDatabaseWrapper db;   // The SQLite DB is in memory
     db.Open();
-    ServerContext context(db, storage, true /* running unit tests */, 10, false /* readonly */, 1 /* DCMTK concurrent transcoders */);
+    ServerContext context(db, storage, true /* running unit tests */, 10, false /* readonly */);
     context.SetupJobsEngine(true, false);
     context.SetCompressionEnabled(compression);
 
--- a/OrthancServer/UnitTestsSources/ServerJobsTests.cpp	Tue May 19 14:00:46 2026 +0200
+++ b/OrthancServer/UnitTestsSources/ServerJobsTests.cpp	Tue May 19 15:14:48 2026 +0200
@@ -566,7 +566,7 @@
       storage_(new MemoryStorageArea)
     {
       db_.Open();
-      context_.reset(new ServerContext(db_, storage_, true /* running unit tests */, 10, false /* readonly */, 1 /* DCMTK concurrent transcoders */));
+      context_.reset(new ServerContext(db_, storage_, true /* running unit tests */, 10, false /* readonly */));
       context_->SetupJobsEngine(true, false);
     }