草庐IT

c++ - 将 Windows 命名管道与 ffmpeg 管道一起使用

coder 2024-06-14 原文

我正在尝试使用 Windows 管道将数据写入 FFmpeg 中的输入管道。我正在为 FFmpeg 使用以下命令:

ffmpeg -r 24 -pix_fmt rgba -s 1280x720 -f rawvideo -y -i \\.\pipe\videopipe -f s16le -ac 1 -ar 44100 -i \\.\pipe\audiopipe -acodec pcm_s16le -ac 1 -b:a 320k -ar 44100 -vf vflip -vcodec mpeg1video -qscale 4 -bufsize 500KB -maxrate 5000KB OUTPUT_FILE

我尝试使用 CreateFile() 方法连接到它,但这似乎不起作用。在开始运行 ffmpeg 命令后,我也尝试过使用 CreateNamedPipe(),但它似乎在等待其他连接。

我不知道我必须按什么顺序调用这两个。我是否首先需要创建一个 Windows 管道并在 FFmpeg 中使用相同的名称,或者我是否需要首先使用命名管道调用 FFmpeg,然后使用 CreateFile() 连接到它?

最佳答案

我已经开发了代码来执行此操作,也许它会有所帮助。在我的例子中,我正在流式传输图像并在 ffplay 中播放它。我启动了 3 个线程,一个创建管道(在演示管道中执行“initializePipe”的线程)一个监听管道创建并启动 ffplay 的线程,以及将图像写入管道的编写器线程。

demoPipes.cpp

#include "demoPipes.h"
using namespace std;

#define MAX_THREADS 100
//#define BUF_SIZE 255

void ErrorHandler(LPTSTR lpszFunction);

// Sample custom data structure for threads to use.
// This is passed by void pointer so it can be any data type
// that can be passed using a single void pointer (LPVOID).
/*typedef struct MyData {
    int val1;
    int val2;
} MYDATA, *PMYDATA;
*/

typedef struct
{
    HANDLE pipe;
    LPCSTR MEDIA_PIPE;
} Session;


int _tmain()
{
    Session* s = (Session*)malloc(sizeof(Session));

    s->pipe = NULL;
    s->MEDIA_PIPE = "\\\\.\\pipe\\screenRec";

    DWORD   dwThreadIdArray[MAX_THREADS];
    HANDLE  hThreadArray[MAX_THREADS]; 

    // Create MAX_THREADS worker threads.
    for( int i=0; i<MAX_THREADS; i++ )
    {
        //create pipe initializer thread
        if(i==0){
            hThreadArray[i] = CreateThread( 
                NULL,                   // default security attributes
                0,                      // use default stack size  
                initializePipe,       // thread function name
                (LPVOID) s,          // argument to thread function 
                0,                      // use default creation flags 
                &dwThreadIdArray[i]);   // returns the thread identifier 
        }

        //create writer thread
        if(i>1){
            PipeMetaData* pipe_data1 = fetch_file("D:\\images.png", s->pipe);
            //PipeMetaData* pipe_data = createPipeMetaData(pipe_data1->file_vector,pipe_data1->byte_size);
            //pipe_data1->pipe =s->pipe; 
            hThreadArray[i] = CreateThread( 
                NULL,                   // default security attributes
                0,                      // use default stack size  
                send_media_to_recorder,       // thread function name
                pipe_data1,          // argument to thread function 
                0,                      // use default creation flags 
                &dwThreadIdArray[i]);   // returns the thread identifier 
        }
        //create recorder thread
        if(i==1){
            hThreadArray[i] = CreateThread( 
                NULL,                   // default security attributes
                0,                      // use default stack size  
                recorder_pipe_function,       // thread function name
                0,          // argument to thread function 
                0,                      // use default creation flags 
                &dwThreadIdArray[i]);   // returns the thread identifier 
        }

        // Check the return value for success.
        // If CreateThread fails, terminate execution. 
        // This will automatically clean up threads and memory. 

        if (dwThreadIdArray[i] == NULL) 
        {
           ErrorHandler(TEXT("CreateThread"));
           ExitProcess(3);
        }
    } // End of main thread creation loop.


    //for close RTP
    // Wait until all threads have terminated.
    WaitForMultipleObjects(MAX_THREADS, hThreadArray, TRUE, INFINITE);

    // Close all thread handles and free memory allocations.
    CloseHandle(s->pipe);
    for(int i=0; i<MAX_THREADS; i++)
    {
        CloseHandle(hThreadArray[i]);
    }
    getchar();
    return 0;
}


void ErrorHandler(LPTSTR lpszFunction) 
{ 
    // Retrieve the system error message for the last-error code.

    LPVOID lpMsgBuf;
    LPVOID lpDisplayBuf;
    DWORD dw = GetLastError(); 

    FormatMessage(
        FORMAT_MESSAGE_ALLOCATE_BUFFER | 
        FORMAT_MESSAGE_FROM_SYSTEM |
        FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,
        dw,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        (LPTSTR) &lpMsgBuf,
        0, NULL );

    // Display the error message.

    lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT, 
        (lstrlen((LPCTSTR) lpMsgBuf) + lstrlen((LPCTSTR) lpszFunction) + 40) * sizeof(TCHAR)); 
    StringCchPrintf((LPTSTR)lpDisplayBuf, 
        LocalSize(lpDisplayBuf) / sizeof(TCHAR),
        TEXT("%s failed with error %d: %s"), 
        lpszFunction, dw, lpMsgBuf); 
    MessageBox(NULL, (LPCTSTR) lpDisplayBuf, TEXT("Error"), MB_OK); 

    // Free error-handling buffer allocations.

    LocalFree(lpMsgBuf);
    LocalFree(lpDisplayBuf);
}

客户端管道.cpp

#include "client_pipe.h"
using namespace std;

DWORD WINAPI recorder_pipe_function( LPVOID lpParam){
    const char* MEDIA_PIPE =  "\\\\.\\pipe\\screenRec";
    //LPCWSTR MEDIA_PIPE_wchar = L"\\\\.\\pipe\\screenRec";

    //waits for server to initialize the media pipe.
    //wait_for_media_pipe(MEDIA_PIPE,10);
    WaitNamedPipeA(MEDIA_PIPE,1000);
    start_recording_session(MEDIA_PIPE);

    return 0;
}

void start_recording_session(const char* media_pipe){
    //initialize recording command
    char* command = (char*)malloc(sizeof(char)*100+1);
    command[0] ='\0';
    strcpy_s(command,sizeof(char)*100+1,"start ffplay -i ");
    //strcpy_s(command,sizeof(char)*100+1,"ffmpeg -i ");
    strcat_s(command,sizeof(char)*100+1, media_pipe);
    //strcat_s(command,sizeof(char)*100+1, " -f matroska D:\\djhfifj.mkv");  
    std::cout << "Executing ffmpeg command\n";
    int i=system (command);
    std::cout << "The value returned was: " << i << std::endl;
}

服务器管道.cpp

#include "server_pipe.h"

using namespace std;

typedef struct
{
    HANDLE pipe;
    LPCSTR MEDIA_PIPE;
} Session;

DWORD WINAPI initializePipe( LPVOID lpParam ) {

    printf("Creating an instance of a named pipe...");

    Session* s = (Session*) lpParam;
    LPCSTR MEDIA_PIPE = s->MEDIA_PIPE;

    // Create a pipe to send data
    s->pipe = CreateNamedPipeA(
        MEDIA_PIPE, // name of the pipe
        PIPE_ACCESS_OUTBOUND, // 1-way pipe -- send only
        PIPE_TYPE_BYTE, // send data as a byte stream
        1, // only allow 1 instance of this pipe
        0, // no outbound buffer
        0, // no inbound buffer
        0, // use default wait time
        NULL // use default security attributes
    );

    if (s->pipe == NULL ||s->pipe == INVALID_HANDLE_VALUE) {
        wcout << "Failed to create outbound pipe instance.";
        // look up error code here using GetLastError()
        return NULL;
    }

    wcout << "Waiting for a client to connect to the pipe..." << endl;

    // This call blocks until a client process connects to the pipe
    BOOL result = ConnectNamedPipe(s->pipe, NULL);
    if (!result) {
        wcout << "Failed to make connection on named pipe." << endl;
        // look up error code here using GetLastError()
        CloseHandle(s->pipe); // close the pipe
        system("pause");
        return NULL;
    }
}

PipeMetaData* fetch_file(char* file_path,HANDLE pipe){
    PipeMetaData* data = (PipeMetaData*) malloc(sizeof(PipeMetaData));

    //opening file
    ifstream infile;
    infile.open(file_path,std::ios::binary);
    infile.seekg(0,std::ios::end);

    //get file byte size
    data->byte_size = infile.tellg();

    //fetch data to send
    data->file_vector =(char*) malloc(sizeof(char)*data->byte_size);
    infile.seekg(0,std::ios::beg);
    infile.read(&(data->file_vector)[0],data->byte_size);
    data->packet = &(data->file_vector)[0];
    data->pipe = pipe;
    wcout<<data->byte_size<<endl;

    return data;
}

DWORD WINAPI send_media_to_recorder(LPVOID lpParam){
    PipeMetaData* p = (PipeMetaData*) lpParam;
    // This call blocks until a client process reads all the data
    DWORD numBytesWritten = 0;
    BOOL result = WriteFile(
        p->pipe, // handle to our outbound pipe
        p->packet,//&(p->file_vector)[0], // data to send
        p->byte_size, // length of data to send (bytes)
        &numBytesWritten, // will store actual amount of data sent
        NULL // not using overlapped IO
    );

    if (result) {
        wcout << "Number of bytes sent: " << numBytesWritten << endl;
    } else {
        wcout << "Failed to send data." << endl;
        // look up error code here using GetLastError()
        GetLastError();
    }

    free(p);
    return 0;
}

关于c++ - 将 Windows 命名管道与 ffmpeg 管道一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28473238/

有关c++ - 将 Windows 命名管道与 ffmpeg 管道一起使用的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  3. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  4. ruby-on-rails - 使用 Ruby on Rails 进行自动化测试 - 最佳实践 - 2

    很好奇,就使用ruby​​onrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提

  5. ruby - 在 Ruby 中使用匿名模块 - 2

    假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于

  6. ruby - 使用 ruby​​ 和 savon 的 SOAP 服务 - 2

    我正在尝试使用ruby​​和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我

  7. ruby - 在 Ruby 程序执行时阻止 Windows 7 PC 进入休眠状态 - 2

    我需要在客户计算机上运行Ruby应用程序。通常需要几天才能完成(复制大备份文件)。问题是如果启用sleep,它会中断应用程序。否则,计算机将持续运行数周,直到我下次访问为止。有什么方法可以防止执行期间休眠并让Windows在执行后休眠吗?欢迎任何疯狂的想法;-) 最佳答案 Here建议使用SetThreadExecutionStateWinAPI函数,使应用程序能够通知系统它正在使用中,从而防止系统在应用程序运行时进入休眠状态或关闭显示。像这样的东西:require'Win32API'ES_AWAYMODE_REQUIRED=0x0

  8. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  9. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  10. ruby - 使用 ruby​​ 将 HTML 转换为纯文本并维护结构/格式 - 2

    我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h

随机推荐