程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python & c++ mixed call programming comprehensive practice -30 start the thread to call the read read view frame function of pyffmpeg extension library

編輯:Python

author : Empty bad uncle
Blog :https://xuhss.com

The breakfast shop won't be open till night , The people who want to eat have already come !

Start thread call pyffmpeg Extension of library Read Read view frame function

One 、pyffmpeg Extension of library Read Read view frame function add

XFFmpeg.h Add a function to read video frames

#pragma once
struct AVFormatContext;
struct AVPacket;
class XFFmpeg
{

public:
// Open the video 
bool Open(const char *url);
// Read a burst of video Store... Internally 
bool Read();
XFFmpeg();
~XFFmpeg();
int totalms = 0;
protected:
// Unpack context 
AVFormatContext *ic = 0;
// Read video frames 
AVPacket *pkt = 0;
};

XFFmpeg.cpp Add function implementation

#include "XFFmpeg.h"
#include <stdio.h>
extern "C" {

#include "libavformat\avformat.h"
}
bool XFFmpeg::Open(const char *url)
{

printf("XFFmpeg::open %s\n", url);
// Open the video decapsulation 
int re =avformat_open_input(&ic, url, 0, 0);
if (re != 0)
{

char buf[1024] = {
 0 };
av_strerror(re, buf, 1023);
printf("avformat open fail:%s\n", buf);
return false;
}
// Get stream 
avformat_find_stream_info(ic, 0);
// Total duration of video acquisition 
this->totalms = ic->duration / (AV_TIME_BASE / 1000);
printf("Total Ms =%d\n", totalms);
return true;
}
bool XFFmpeg::Read()
{

if (!ic)
return false;
// Storage space of video frames 
if (!pkt)
{

// Allocate object space 
pkt = av_packet_alloc();
}
else
{

// Reference count -1 Clean up video frames 
av_packet_unref(pkt);
}
int re = 0;
bool isFindVideo = false;
// Audio data lost 
for (int i = 0; i < 20; i++)
{

// Read a frame of data 
re = av_read_frame(ic, pkt);
// Read failed or read to the end of the file 
if (re != 0)
{

return false;
}
// Is it a video frame 
if (pkt->stream_index == 0)
{

isFindVideo = true;
break;
}
// Audio frame clear packet
av_packet_unref(pkt);
}
return isFindVideo;
}
XFFmpeg::XFFmpeg()
{

printf("Create XFFmpeg\n");
}
XFFmpeg::~XFFmpeg()
{

printf("Delete XFFmpeg\n");
}

PyFFmpeg.h Open interface , convenient python call

#pragma once
#include<Python.h>
class XFFmpeg;
class PyFFmpeg
{

public:
PyObject_HEAD
XFFmpeg *ff;
// Open to python Function of 
public:
static PyObject *Create(PyTypeObject *type, PyObject *args, PyObject *kw);
static int Init(PyFFmpeg*self, PyObject *args, PyObject *kw);
static void Close(PyFFmpeg*self);
static PyObject* Open(PyFFmpeg*self, PyObject*args);
static PyObject *Read(PyFFmpeg*self, PyObject*args);
// Property function get
static PyObject* GetTotalms(PyFFmpeg*self, void*closure);
};

PyFFmpeg.cpp Open interface implementation add implementation and registration

#include "PyFFmpeg.h"
#include "XFFmpeg.h"
// Open to python
PyObject *PyFFmpeg::Create(PyTypeObject *type, PyObject *args, PyObject *kw) {

printf("PyFFmpeg::Create\n");
PyFFmpeg*f = (PyFFmpeg*)type->tp_alloc(type, 0);
f->ff = new XFFmpeg();
return (PyObject *)f;
}
int PyFFmpeg::Init(PyFFmpeg*self, PyObject *args, PyObject *kw)
{

printf("PyFFmpeg::Init\n");
return 0;
}
void PyFFmpeg::Close(PyFFmpeg*self)
{

printf("PyFFmpeg::Close\n");
delete self->ff;
Py_TYPE(self)->tp_free(self);
}
PyObject *PyFFmpeg::Read(PyFFmpeg*self, PyObject*args)
{

if (!self->ff)
Py_RETURN_FALSE;
if (self->ff->Read())
Py_RETURN_TRUE;
Py_RETURN_FALSE;
}
PyObject* PyFFmpeg::Open(PyFFmpeg*self, PyObject*args)
{

const char *url = NULL;
if (!PyArg_ParseTuple(args, "s", &url))
return NULL;
printf("PyFFmpeg::Open %s\n", url);
if (self->ff->Open(url))
Py_RETURN_TRUE;
Py_RETURN_FALSE;
}
PyObject* PyFFmpeg::GetTotalms(PyFFmpeg*self, void*closure)
{

return PyLong_FromLong(self->ff->totalms);
}
// Module entry Module name pyffmpeg
PyMODINIT_FUNC PyInit_pyffmpeg(void)
{

PyObject *m = NULL;
static PyModuleDef ffmod = {

PyModuleDef_HEAD_INIT,
"pyffmpeg",
"", -1, 0
};
m = PyModule_Create(&ffmod);
// add to PyFFmpeg_python class 
static PyTypeObject type;
memset(&type, 0, sizeof(PyFFmpeg));
type.ob_base = {
 PyObject_HEAD_INIT(NULL) 0 };
type.tp_name = "";
type.tp_basicsize = sizeof(PyFFmpeg);
type.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE;
type.tp_new = PyFFmpeg::Create;
type.tp_init = (initproc)PyFFmpeg::Init;
type.tp_dealloc = (destructor)PyFFmpeg::Close;
static PyMethodDef ffmeth[] = {

{
 "open", (PyCFunction)PyFFmpeg::Open, METH_VARARGS, "" },
{
 "read", (PyCFunction)PyFFmpeg::Read, METH_NOARGS, "" },
{
 NULL }
};
type.tp_methods = ffmeth;
static PyGetSetDef sets[] = {

{
 "totalms", (getter)PyFFmpeg::GetTotalms, 0, 0,0 },
{
 NULL }
};
type.tp_getset = sets;
// Initialization type 
if (PyType_Ready(&type) < 0) {

return NULL;
}
PyModule_AddObject(m, "PyFFmpeg", (PyObject*)&type);
printf("Pyinit_pyffmpeg\n");
return m;
}

pyqt.py Add a call to the interface

isRunning = True
# The main function Called in subthread , Thread is c++ establish 
def main():
print("Python main")
global ff;
while isRunning:
print(ff.read());

Two 、 Open the thread to call the extension library interface

2.1 Do not start thread calling

pyplayer.cpp Invocation in constructor main Function call Threads are not enabled here

PyPlayer::PyPlayer(QWidget *parent)
: QWidget(parent)
{

ui.setupUi(this);
Py_SetPythonHome(L"./");
Py_Initialize();
// Loading module 
pModule = PyImport_ImportModule("pyqt");
if (!pModule)
{

printf("PyImport import error");
PyErr_Print();
return;
}
// obtain python Configuration item Change the size and title of the window 
PyObject *conf = PyObject_GetAttrString(pModule, "conf");
if (!conf)
{

cout << "Please set the conf" << endl;
PyErr_Print();
return;
}
PyObject *key = PyUnicode_FromString("width");
int width = PyLong_AsLong(PyDict_GetItem(conf, key));
Py_XDECREF(key);
key = PyUnicode_FromString("height");
int height = PyLong_AsLong(PyDict_GetItem(conf, key));
Py_XDECREF(key);
// Change window title 
key = PyUnicode_FromString("title");
wchar_t title[1024] = {
 0 };
PyUnicode_AsWideChar(PyDict_GetItem(conf, key), title, 1023);
this->setWindowTitle(QString::fromUtf16((char16_t*)title));
Py_XDECREF(key);
if (width > 0 && height > 0)
{

resize(width, height);
}
Py_XDECREF(conf);
// Open the interface for selecting files to python
static PyMethodDef meths[] = {

{
 "OpenDialog", (PyCFunction)OpenDialog, METH_NOARGS, 0 }
,{
 NULL }
};
int re = PyModule_AddFunctions(pModule, meths);
if (!re)
{

PyErr_Print();
}
// Open thread call python Of main function 
PyObject*main_fun = PyObject_GetAttrString(pModule, "main");
if (!main_fun || !PyCallable_Check(main_fun))
{

cout << "main_fun get failed!" << endl;
return;
}
if (PyObject_CallObject(main_fun, 0))
{

PyErr_Print();
return;
}
}

function , You will find that it always outputs false, And the main thread is stuck , Because it's in a thread ,python Of main Function has a loop , A loop that does not exit .

2.2 Start thread call to read video

Add a thread function run_main, And will be implemented main The code of the function is put into this thread

#include <Python.h>
#include "PyPlayer.h"
#include <iostream>
#include <QFileDialog>
#include <thread>
using namespace std;
static PyObject *pModule = 0;
// Returns the selected file path 
PyObject* OpenDialog(PyObject *self)
{

QString fileName = "";
fileName = QFileDialog::getOpenFileName();
if (fileName.isEmpty())
return PyUnicode_FromString("");
return PyUnicode_FromString(fileName.toStdString().c_str());
}
void PyPlayer::Open() {

cout << "PyPlayer::Open()" << endl;
// call Python Of open function 
if (!pModule) return;
PyObject *open = PyObject_GetAttrString(pModule, "open");
if (!open || !PyCallable_Check(open))
{

PyErr_Print();
return;
}
PyObject_CallObject(open, 0);
}
void run_main()
{

PyObject*main_fun = PyObject_GetAttrString(pModule, "main");
if (!main_fun || !PyCallable_Check(main_fun))
{

cout << "main_fun get failed!" << endl;
return;
}
if (PyObject_CallObject(main_fun, 0))
{

PyErr_Print();
return;
}
}
PyPlayer::PyPlayer(QWidget *parent)
: QWidget(parent)
{

ui.setupUi(this);
Py_SetPythonHome(L"./");
Py_Initialize();
// Loading module 
pModule = PyImport_ImportModule("pyqt");
if (!pModule)
{

printf("PyImport import error");
PyErr_Print();
return;
}
// obtain python Configuration item Change the size and title of the window 
PyObject *conf = PyObject_GetAttrString(pModule, "conf");
if (!conf)
{

cout << "Please set the conf" << endl;
PyErr_Print();
return;
}
PyObject *key = PyUnicode_FromString("width");
int width = PyLong_AsLong(PyDict_GetItem(conf, key));
Py_XDECREF(key);
key = PyUnicode_FromString("height");
int height = PyLong_AsLong(PyDict_GetItem(conf, key));
Py_XDECREF(key);
// Change window title 
key = PyUnicode_FromString("title");
wchar_t title[1024] = {
 0 };
PyUnicode_AsWideChar(PyDict_GetItem(conf, key), title, 1023);
this->setWindowTitle(QString::fromUtf16((char16_t*)title));
Py_XDECREF(key);
if (width > 0 && height > 0)
{

resize(width, height);
}
Py_XDECREF(conf);
// Open the interface for selecting files to python
static PyMethodDef meths[] = {

{
 "OpenDialog", (PyCFunction)OpenDialog, METH_NOARGS, 0 }
,{
 NULL }
};
int re = PyModule_AddFunctions(pModule, meths);
if (!re)
{

PyErr_Print();
}
// Open thread call python Of main function 
std::thread t1(run_main);
t1.detach();
}

In execution , The interface comes out :

Click the open button Found that the program crashed :

2.3 Add global GIL lock , Prevent software from crashing

stay PyPlayer.cpp in open Function to add gil lock

void PyPlayer::Open() {

cout << "PyPlayer::Open()" << endl;
// call Python Of open function 
if (!pModule) return;
PyGILState_STATE gil;
gil = PyGILState_Ensure();
PyObject *open = PyObject_GetAttrString(pModule, "open");
if (!open || !PyCallable_Check(open))
{

PyErr_Print();
PyGILState_Release(gil);
return;
}
PyObject_CallObject(open, 0);
PyGILState_Release(gil);
}

Run again and you won't crash .

2.4 The console visualizes the process of reading video

modify pyqt.py The process of reading video is output point by point , In this way, you can verify that the read thread is ok

print("Python PyPlayer")
from pyffmpeg import *
import time
conf = {

"width" : 1280,
"height" : 720,
"title" : "PyPlayer player "
}
ff = PyFFmpeg()
def open():
global ff;
print("Python open")
filename = OpenDialog()
if ff.open(filename):
print("open file success!")
else:
print("open file failed!")
print(filename)
isRunning = True
# The main function Called in subthread , Thread is c++ establish 
def main():
print("Python main")
global ff;
while isRunning:
#print(ff.read())
re = ff.read()
if re:
print(".", end='', flush = True) #flush Output buffer 
time.sleep(0.02)
else:
time.sleep(1)

3、 ... and 、 summary

  • This article starts thread calling pyffmpeg Extension of library Read Read view frame function .
  • If you think the article is useful to you , Remember give the thumbs-up Collection forward A wave , Bloggers also support making exclusive dynamic wallpapers for iron fans ~

Share high-quality articles in previous periods

  • C++ QT combination FFmpeg Actual development of video player -01 Environment installation and project deployment
  • solve QT problem : function qmake:Project ERROR: Cannot run compiler ‘cl‘. Output:
  • Resolve installation QT after MSVC2015 64bit No compiler and debugger issues with configuration
  • Qt Kit tips in no complier set in kit and no debugger, The yellow exclamation mark appears and the problem is solved (MSVC2017)
  • Python+selenium automation - Realize automatic import 、 Upload external files ( Don't pop up windows window )

High quality tutorial sharing

  • If you don't enjoy reading the article , You can come to my other special column Take a look ~
  • For example, the following columns :Python Actual wechat ordering applet 、Python Quantitative trading practice 、C++ QT Practical projects and Algorithm learning column
  • You can learn more about C++/Python Relevant contents of ! Directly click on the color font below to jump !
Learning route guidance ( Click unlock ) Knowledge orientation Crowd positioning 🧡 Python Actual wechat ordering applet 🧡 Progressive class This course is python flask+ Perfect combination of wechat applet , From the deployment of Tencent to the launch of the project , Create a full stack ordering system .Python Quantitative trading practice beginner Take you hand in hand to create an easy to expand 、 More secure 、 More efficient Quantitative trading System ️ C++ QT combination FFmpeg Actual development of video player ️ The difficulty is high Sharing learning QT Finished video player source code , We need to have a solid C++ knowledge ! A community of 90000 game lovers Help each other / Blow water 90000 game lovers community , Chat and help each other , White whoring prize Python Zero basis to introduction Python beginner For small partners who have not been systematically studied , The core purpose is to enable us to learn quickly Python Knowledge to get started

Data white whoring , reminder

Follow the card below to get more programming knowledge immediately , Including various language learning materials , Thousands of sets PPT Templates and various game source materials and so on . More information can be viewed by yourself !


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved