wpf icon indicating copy to clipboard operation
wpf copied to clipboard

Flickering when updating WritableBitmap

Open Yonch404 opened this issue 1 year ago • 11 comments

I'm developing a large-scale application with a custom rendering system. The system has a dedicated rendering thread that draws a specific region of a virtual canvas into a temporary memory buffer. Then, in the OnRender() method, I use WritableBitmap.WritePixels() to update the image content, and draw it to a specified screen region using DrawingContext.DrawImage()

During user interactions such as mouse dragging, the draw region changes in real time, but the actual image content is not necessarily updated on every OnRender() call.

I've noticed that occasionally, the image content does not match the drawn region, resulting in visible "jumps" or flickering during dragging. This issue is especially noticeable on my 4K display with integrated graphics, full-screen window, where the flickering happens frequently.

Interestingly, I encountered the same issue when previously using InteropBitmap, which also involves a updating image data mechanism. This leads me to believe the issue is related to how images with such updating mechanisms.

When I switched to creating a new BitmapSource in every 'OnRender()' call and drawing it directly—without using WritableBitmap—the issue disappeared entirely. This strongly suggests that WritableBitmap.WritePixels() is not synchronized with the OnRender() pipeline under certain conditions.

I also tried using Dispatcher.Invoke with DispatcherPriority.Render to call WritePixels(), but the problem persists.

It seems that under heavy rendering load, the image updated by WritePixels() might not be synchronized with the draw operation in OnRender(), leading to this visual mismatch.

How can I avoid this timing issue while still using WritableBitmap?

Yonch404 avatar Aug 02 '25 18:08 Yonch404

I don't think there is any guarantee anywhere that would justify your expectations of synchronization here. A repro sample would also be helpful.

Could you not have the destination be a WriteableBitmap rather than using DrawingContext?

miloush avatar Aug 02 '25 19:08 miloush

Yes, it seems there’s no guarantee that updating the content of WritableBitmap is synchronized with the rendering via DrawingContext.

Most typical use cases for WritableBitmap involve only updating the pixel content, while the drawing position remains fixed. However, in my scenario, the drawing region needs to change frequently. I’m working with a large virtual canvas, and only render the currently visible portion of it. A single render can take around 300ms. Therefore, when the user pans or zooms with the mouse, I need to immediately offset the image to the new position in OnRender() to maintain a smooth experience—even if the rendered content for the new region arrives later. Otherwise, panning would be limited to 10 FPS.

Technically, I could update only the contents of the WritableBitmap, but that would require manually translating and scaling the image on the CPU for every frame and then using WritePixels to update it, which may perform worse than directly creating a new BitmapSource every time.

I’ve tried creating a demo, but it doesn't seem to reproduce the issue unless there’s rendering load, which is more apparent in my large application, and in VisualStudio debugging the WPF application.

From a design perspective, this seems to be an inherent limitation—WritableBitmap/InteropBitmap/D3DImage all use update mechanisms that differ from traditional rendering paths. While this is part of what makes them fast and efficient, it also seems to be the cause of this desynchronization issue.

Yonch404 avatar Aug 02 '25 20:08 Yonch404

The main code is as follows:

   private WriteableBitmap? _bitmap;
   private RenderInfo? _renderInfo;
   
   private void OnAsyncRenderFinished(object? sender, RenderInfo e)
   {
      // in the render thread, switch to UI thread
      Dispatcher.Invoke(() =>
      {
         if (!IsLoaded || _target == null) return;

         _renderInfo = e;
         var bmp = _target.SkBitmap;
         if (_bitmap == null || bmp.Width != _bitmap.PixelWidth || bmp.Height != _bitmap.PixelHeight)
            _bitmap = new WriteableBitmap(bmp.Width, bmp.Height, _dpiX, _dpiY, PixelFormats.Bgra32, null);

         _bitmap.WritePixels(new Int32Rect(0, 0, bmp.Width, bmp.Height), bmp.GetPixels(), bmp.ByteCount, bmp.RowBytes);
         InvalidateVisual();
      });
   }
   
   protected override void OnRender(DrawingContext context)
   {
      base.OnRender(context);

      context.DrawRectangle(Brushes.Transparent, null, new Rect(RenderSize));

      if (_bitmap == null || _renderInfo == null ||
          _dpiX <= 0 || _dpiY <= 0) return;

      // without (zooming && bitmap is old), is 1.0
      var drawScale = Scale / _renderInfo.ScaleX;
      var drawWid = _bitmap.PixelWidth * 96 / _dpiX * drawScale;
      var drawHei = _bitmap.PixelHeight * 96 / _dpiY * drawScale;

      // without (panning && bitmap is old), is 0,0
      var drawOffsetX = (OffsetX - _renderInfo.OffsetX) * ScaleWithDpi;
      var drawOffsetY = (OffsetY - _renderInfo.OffsetY) * ScaleWithDpi;

      context.DrawImage(_bitmap, new Rect(drawOffsetX, drawOffsetY, drawWid, drawHei));
   }

Yonch404 avatar Aug 02 '25 20:08 Yonch404

I am assuming the reason you don't want to be creating new bitmaps each render is to avoid allocating a lot of memory all the time. Could you not have a pre-allocated buffer that you keep writing to, but create like an InteropBitmap wrapper around it for rendering? You might even be able to use the WriteableBitmap's back buffer for the storage, or if I understand it correctly, you already have it in the _target.SkBitmap.GetPixels(). So instead of going through WriteableBitmap, you could directly use the pointer in CreateBitmapSourceFromMemorySection?

miloush avatar Aug 02 '25 20:08 miloush

Actually, my initial implementation used InteropBitmap. However, I encountered the same flickering issue due to the GPU presenting the updated image at a different time than OnRender.

Simply put, OnAsyncRenderFinished produces a new frame roughly every 300ms. In between, any visual movement during user dragging is purely controlled by the target region passed to DrawImage.

Therefore, the display must show either the new image+new offset, or the old image+old offset , anything mismatched image and offset causes visual flickering.

Yonch404 avatar Aug 02 '25 21:08 Yonch404

Ah, you need the position match, I see. Yeah WPF rendering model does not give you direct access to what is on the screen, OnRender isn't technically related to showing stuff on the screen this way. Could you not have two buffers (including the position) and swap them when the rendering is done (using the ContentRendered event)?

miloush avatar Aug 02 '25 21:08 miloush

WPF doesn't support immediate buffer swapping. When calling WritableBitmap.Unlock(), it only calls SubscribeToCommittingBatch. On MediaContext.CommittingBatch event, it sending the copy command to the rendering channel, and then calls CloseBatch(). So it seems that WritableBitmap updates are still integrated into the rendering pipeline, not real-time, but for some reason, they don’t appear to be presented together with OnRender().

Yonch404 avatar Aug 02 '25 22:08 Yonch404

What I was suggesting is to give data to OnRender and not change them until you get confirmation the rendering is finished. Meanwhile you can prepare your next frame and positions in second buffer, and then again give them to OnRender and not touch them until rendered. I don't really know the application so I am just throwing random ideas, but it sounds like WPF might not be the best framework for your scenario.

miloush avatar Aug 02 '25 23:08 miloush

There appears to be no way to determine when the frame drawn by OnRender() and the update submitted by WritePixels() have definitively completed rendering. The presentation layer is completely isolated from the user's perspective.

There is a chance that the drawing area submitted by DrawImage() and the image updated by WritePixels() are presented separately. This seems to be a bug in WPF. As this is currently the only viable solution for me, if this cannot be implemented, I will have to resort to creating a new BitmapSource for every draw call.

Another potential solution is to draw the image to the target position and size in a memory buffer beforehand and then only call WritePixels() to update the screen. However, the performance of this approach is very poor, even worse than creating a new BitmapSource every time.

Yonch404 avatar Aug 06 '25 16:08 Yonch404

@IDXGI I've recently revisited the source code for WritableBitmap, and I believe your conclusion may be incorrect. In WPF, when writing data to a WritableBitmap, it should be done between the Lock and Unlock calls. These two methods are specifically designed to synchronize with the rendering thread; the rendering thread itself performs similar locking and unlocking operations. Between Lock and Unlock, the contents of WritableBitmap are copied into m_pBackBuffer. During actual rendering, m_pBackBuffer is used, which essentially means this is a double-buffered design—so flickering shouldn't occur. If you do encounter flickering, it's likely because your application logic isn't properly synchronized with rendering; for example, an animation intended to be smooth might actually be implemented as a series of discrete steps. If I've misunderstood anything here, please let me know.

lindexi avatar Aug 21 '25 00:08 lindexi

@lindexi You're absolutely right. For the content update alone, the double-buffering mechanism in WriteableBitmap is perfectly capable of preventing flickering.

The issue I'm facing is more nuanced. My scenario requires that a specific rendered frame's content must be perfectly synchronized with its corresponding drawing region for that same frame. The flickering I described—or more accurately, the visual "jitter"—occurs when there's a mismatch:

  • The new bitmap content is displayed at the previous frame's screen region.
  • Or, the old bitmap content is displayed at the new frame's screen region.

This means that the content update from WritePixels() and the drawing region submitted by DrawImage() must be applied atomically within the same presentation frame. Under light rendering load, this usually works correctly. However, on a 4K display with integrated graphics, the jitter becomes frequent.

I've recently been studying the WPF source code and believe I've found a potential cause. When updating a WriteableBitmap, it appears that within a single Channel.Commit(), there are always two Batch created. I'm not an expert on how multiple batches are processed after submission (maybe in the WpfGfx?), but I've observed the generation sequence:

  1. First, all OnRender() methods are executed, generating drawing commands for the first batch. Channel.CloseBatch() is then called.
  2. Subsequently, the MediaContext.CommittingBatch event is raised. In response, WriteableBitmap sends a MilCmdDoubleBufferedBitmapCopyForward command for the second batch and immediately calls CloseBatch().
  3. After these steps are completed, MediaContext calls Channel.Commit().

This process leads to a potential race condition on the render thread. Within a single rendering cycle for a frame, the UI thread generates at least two related commands:

  • Command A (DrawImage): Originating from the OnRender method, this command instructs the render thread: "Draw using the WriteableBitmap's front buffer at a specific location."
  • Command B (COPYFORWARD): Originating from the WriteableBitmap.OnCommittingBatch(), this command instructs the render thread: "Copy the contents of the WriteableBitmap's back buffer to its front buffer."

The render thread receives these commands but there is no mechanism to guarantee that Command B executes before Command A.

Under high system load, the render thread's processing can lag behind the UI thread's submissions. It might receive the commands for Frame N and perform the following sequence:

  1. It first processes Command A (DrawImage). At this moment, it uses the WriteableBitmap's front buffer, which still contains the content from Frame N-1.
  2. Afterward, it processes Command B (COPYFORWARD). Only now is the new content for Frame N copied from the back buffer to the front buffer.

The result is that the content from Frame N-1 is displayed at the screen position intended for Frame N. The visuals only "catch up" when the DrawImage command for Frame N+1 is processed, which finally uses the updated front buffer. This one-frame desynchronization is the source of the visual jitter.

Perhaps this situation is something the WPF designers didn't consider, and InteropBitmap also has this problem. However, for the same code, I can solve it by switching to BitmapSource.Create, because it ensures that the screen content and the DrawImage area are rendered at the same time, but this also prevents me from getting the performance advantage of WriteableBitmap.

Yonch404 avatar Aug 21 '25 12:08 Yonch404