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 !
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());
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 .
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 :
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 .
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)
give the thumbs-up
Collection
forward
A wave , Bloggers also support making exclusive dynamic wallpapers for iron fans ~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 !