MediaFrameReader 在设置 MJPG 格式时抛出 ArgementException?

MediaFrameReader throws ArgementException when setting MJPG format?

我正在尝试从网络摄像头获取每一帧的位图。

我遵循了这个 Microsoft 教程 Process media frames with MediaFrameReader。其他一些视频格式(YUY2、NV12...)工作正常,但选择和设置 MJPG 格式将导致 ArgumentException: 'Value does not fall within the expected range.'MediaFrameReader.TryAcquireLatestFrame()

这是我设置网络摄像头媒体源和处理 FrameArrived 事件的工作代码:

private async Task StartReadFrameAsync()
{
    MediaFrameSourceInfo colorSourceInfo = null;
    MediaFrameSourceGroup selectedGroup = null;
    var frameSourceGroups = await MediaFrameSourceGroup.FindAllAsync();
    foreach (var sourceGroup in frameSourceGroups)
    {
        foreach (var sourceInfo in sourceGroup.SourceInfos)
        {
            if (sourceInfo.MediaStreamType == MediaStreamType.VideoRecord && sourceInfo.SourceKind == MediaFrameSourceKind.Color)
            {
                colorSourceInfo = sourceInfo;
                break;
            }
        }
        if (colorSourceInfo != null)
        {
            selectedGroup = sourceGroup;
            break;
        }
    }

    var settings = new MediaCaptureInitializationSettings
            {
                VideoDeviceId = deviceId, 
                SourceGroup = selectedGroup, 
                MemoryPreference = MediaCaptureMemoryPreference.Cpu
            };
    var mediaCapture = new MediaCapture();
    await mediaCapture.InitializeAsync(settings);

    var colorFrameSource = mediaCapture.FrameSources[colorSourceInfo.Id];
    var preferredFormat = colorFrameSource.SupportedFormats.FirstOrDefault(format =>
    {
        return format.Subtype == MediaEncodingSubtypes.Mjpg && format.VideoFormat.Width >= 720;
    });
    if (preferredFormat == null)    
         return;    

    await colorFrameSource.SetFormatAsync(preferredFormat);
    mediaFrameReader = await mediaCapture.CreateFrameReaderAsync(colorFrameSource, MediaEncodingSubtypes.Mjpg);
    mediaFrameReader.FrameArrived += MediaFrameReader_FrameArrived;
    await mediaFrameReader.StartAsync();
}

private async void MediaFrameReader_FrameArrived(MediaFrameReader sender, MediaFrameArrivedEventArgs args)
{
    var mediaFrameReference = sender.TryAcquireLatestFrame();  // <- throws ArgementException 
    var videoMediaFrame = mediaFrameReference?.VideoMediaFrame;
    var softwareBitmap = videoMediaFrame?.SoftwareBitmap;
    //...
}

我测试了两个网络摄像头,它们支持 MJPG 格式,我还检查了在 CaptureElement 控件中预览 MJPG 格式是否有效。只有 TryAcquireLatestFrame() 事件 MediaFrameReader_FrameArrived 会抛出。

问题:

我做错了什么,MediaFrameReader 无法获取 MJPG 帧?

MediaFrameReader throws ArgementException when setting MJPG format?

请参考官方代码示例here对于颜色源,我们接受任何内容并要求将其转换为 Bgra8

如果要将相机的FrameSource设置为mjpg,请调用SetFormatAsync方法。

 if (format != null && !format.HasSameFormat(_source.CurrentFormat))
 {
    await _source.SetFormatAsync(format.Format);
    _logger.Log($"Format set to {format.DisplayName}");
 }

如果你的相机支持mjpg帧,你也可以使用上面的代码示例测试。 (我的设备:logic camera c310不支持mjpg)