从ffmpeg标准输出的单个流中获取多个图像

时间:2014-09-18 00:33:42

标签: c# ffmpeg stream jpeg stdout

我开始使用ffmpeg

从视频文件中检索几帧
ffmpeg -i "<videofile>.mp4" -frames:v 10 -f image2pipe pipe:1

并将图像传输到stdout -

var cmd = Process.Start(p);
var stream = cmd.StandardOutput.BaseStream;
var img = Image.FromStream(stream);

以这种方式获取第一张图片有效,但我如何获得所有这些?

1 个答案:

答案 0 :(得分:2)

好的,这很容易让我感到尴尬,我在这里问道。我会发布答案,以防它帮助其他人。

每当有新图像时,流中的前几个字节将重复。我猜想前8个会做,瞧。

    static IEnumerable<Image> GetThumbnails(Stream stream)
    {
        byte[] allImages;
        using (var ms = new MemoryStream())
        {
            stream.CopyTo(ms);
            allImages = ms.ToArray();
        }
        var bof = allImages.Take(8).ToArray(); //??
        var prevOffset = -1;
        foreach (var offset in GetBytePatternPositions(allImages, bof))
        {
            if (prevOffset > -1)
                yield return GetImageAt(allImages, prevOffset, offset);
            prevOffset = offset;
        }
        if (prevOffset > -1)
            yield return GetImageAt(allImages, prevOffset, allImages.Length);
    }

    static Image GetImageAt(byte[] data, int start, int end)
    {
        using (var ms = new MemoryStream(end - start))
        {
            ms.Write(data, start, end - start);
            return Image.FromStream(ms);
        }
    }

    static IEnumerable<int> GetBytePatternPositions(byte[] data, byte[] pattern)
    {
        var dataLen = data.Length;
        var patternLen = pattern.Length - 1;
        int scanData = 0;
        int scanPattern = 0;
        while (scanData < dataLen)
        {
            if (pattern[0] == data[scanData])
            {
                scanPattern = 1;
                scanData++;
                while (pattern[scanPattern] == data[scanData])
                {
                    if (scanPattern == patternLen)
                    {
                        yield return scanData - patternLen;
                        break;
                    }
                    scanPattern++;
                    scanData++;
                }
            }
            scanData++;
        }
    }