Russian Qt Forum

Qt => Мультимедиа => Тема начата: Laex от Январь 26, 2009, 20:46



Название: MediaSource из QIODevice
Отправлено: Laex от Январь 26, 2009, 20:46
Хотел реализовать предзагрузку данных из сети... Для этого написал класс наследник QIODevice и передал его конструктору MediaSource. Но, к сожалению, такой приём мне неудался( Ошибка Could not open media source. происходит в функции beginLoad
Код:
void MediaObject::beginLoad()
{
    if (gst_element_set_state(m_pipeline, GST_STATE_PAUSED) != GST_STATE_CHANGE_FAILURE) {
        m_backend->logMessage("Begin source load", Backend::Info, this);
    } else {
        setError(tr("Could not open media source."));
    }
}
Код:
CallStack:
#0  Phonon::Gstreamer::MediaObject::beginLoad (this=0x832f2a8) at ../../../3rdparty/kdebase/runtime/phonon/gstreamer/mediaobject.cpp:900
#1  Phonon::Gstreamer::MediaObject::setSource (this=0x832f2a8, source=) at ../../../3rdparty/kdebase/runtime/phonon/gstreamer/mediaobject.cpp:895
#2  Phonon::MediaObject::setCurrentSource (this=0x832ce88, newSource=) at ../3rdparty/kdelibs/phonon/mediaobject.cpp:255

Те функции которые можно было перегрузить в моём классе, я перегрузил дабы узнать что было вызвано до этого момента. Были вызваны reset и open. OpenMode я поставил ReadOnly. При попытке media->play() получаю errorstring: "Could not decode media source.". Хотя вызовов readData небыло, ровно как и любых других вызовов из QIODevice(
Собственно вопрос - "Что я не так делаю?"
Qt 4.4.0+phonon(gstreamer backend) на Ubuntu(hardy)


Мой класс
Код:
class Prefetcher : public QIODevice {
Q_OBJECT
struct Interval {qint64 be;qint64 en;};
public:
QHttp *http;
qint64 sz;
bool isError;
int spos;
QByteArray buffer;
QBuffer iobuffer;
QByteArray values;
QList<Interval> it;
QEventLoop *loop;
QUrl target;
Prefetcher(QObject *parent);
void addNewInterval(Interval nit);
void setSource(QUrl path);
void wait();

bool atEnd () ;
qint64 bytesAvailable ();
qint64 bytesToWrite ();
bool canReadLine () ;
void close ();
bool isSequential () ;
qint64 pos () ;
bool reset ();
bool seek ( qint64 pos );
bool waitForBytesWritten ( int msecs );
bool waitForReadyRead ( int msecs );
qint64 readLineData ( char * data, qint64 maxSize );

qint64 size();
qint64 readData ( char * data, qint64 maxSize );
qint64 writeData ( const char * data, qint64 maxSize );
bool open (OpenMode mode);
public slots:
void rmove(int);
void rfinish(int,bool);
void rupdate(QHttpResponseHeader);
void setsize(QHttpResponseHeader);
};

bool Prefetcher::atEnd () {
qDebug() << "atEnd";
return QIODevice::atEnd();
}

qint64 Prefetcher::bytesAvailable () {
qDebug() << "bytesAvalible";
return QIODevice::bytesAvailable();
}

qint64 Prefetcher::bytesToWrite () {
qDebug() << "bytesToWrite";
return QIODevice::bytesToWrite();
}

bool Prefetcher::canReadLine () {
qDebug() << "canReadLine";
return QIODevice::canReadLine();
}

void Prefetcher::close () {
qDebug() << "close";
return QIODevice::close();
}

bool Prefetcher::isSequential () {
qDebug() << "isSequential";
return QIODevice::isSequential();
}

qint64 Prefetcher::pos () {
qDebug() << "pos";
return QIODevice::pos();
}

bool Prefetcher::reset () {
qDebug() << "reset";
return QIODevice::reset();
}

bool Prefetcher::seek ( qint64 pos ) {
qDebug() << "seek";
return QIODevice::seek(pos);
}

bool Prefetcher::waitForBytesWritten ( int msecs ) {
qDebug() << "waitForBytesWritten ";
return QIODevice::waitForBytesWritten(msecs);
}

bool Prefetcher::waitForReadyRead ( int msecs ){
qDebug() << "waitForReadyRead ";
return QIODevice::waitForReadyRead (msecs);
}

qint64 Prefetcher::readLineData ( char * data, qint64 maxSize ) {
qDebug() << "readLineData";
return QIODevice::readLineData(data,maxSize);
}

Prefetcher::Prefetcher(QObject *parent) : QIODevice(parent) {
http = new QHttp(parent);
sz = 0;
spos = 0;
isError = false;

QObject::connect(http, SIGNAL(requestFinished(int, bool)),this, SLOT(rfinish(int, bool)));
QObject::connect(http, SIGNAL(readyRead(const QHttpResponseHeader&)),this, SLOT(rupdate(const QHttpResponseHeader&)));
QObject::connect(http, SIGNAL(responseHeaderReceived(const QHttpResponseHeader &)),this, SLOT(setsize(const QHttpResponseHeader &)));

loop= new QEventLoop(parent);

iobuffer.setBuffer(&buffer);
}

bool Prefetcher::open(OpenMode mode) {
qDebug() << "open-begin";
if (QIODevice::ReadOnly==mode) {
setOpenMode(mode);
seek(0);
qDebug() << "open-ok[" << errorString() << "]";
return true;
} else
return false;
}

void Prefetcher::setSource(QUrl path) {
isError = false;
it.clear();
buffer.clear();
spos = 0;
target=path;
http->setHost(target.host(),target.port(80));
rmove(0);
}

void Prefetcher::wait() {
loop->exec();
}

qint64 Prefetcher::size() {
qDebug() << "sizeread";
while(sz==0)
wait();
qDebug() << "size=" << sz;
return sz;
}

qint64 Prefetcher::readData( char * data, qint64 maxSize ) {
qDebug() << "rData" << maxSize << "pos[" <<pos() <<"]";
qDebug() << "it dump";
QString itdump;
for(int z=0;z<it.size();z++)
itdump += QString("[") + QString::number(it[z].be) + QString(",")+QString::number(it[z].en)+QString("]");
qDebug() << itdump;
int idx = -1;
while(idx==-1) {
for(int i=0;i<it.size();i++)//binary search too)
if((it[i].be<=pos())&&(it[i].en>=pos())) {
idx=i;
break;
}
if (idx==-1)
wait();
}
int bava=it[idx].en-pos()+1;
bava=maxSize>bava?maxSize:bava;
char*source=values.data();
source+=pos();
memcpy(data,source,bava);
return bava;
}

qint64 Prefetcher::writeData ( const char * data, qint64 maxSize ) {
Q_UNUSED(data);
Q_UNUSED(maxSize);
return 0;
}

void Prefetcher::rfinish(int id ,bool err) {
Q_UNUSED(id);
Q_UNUSED(err);
loop->exit();
}

void Prefetcher::addNewInterval(Interval nit) {
if (it.size()==0) {
it << nit;
return;
}

int idx=0;
while(it[idx].be<nit.be)
if (it.size()-1==idx)
break;
else
idx++;

if (it[idx].en>=nit.be-1)
it[idx].en=nit.en>it[idx].en?nit.en:it[idx].en;
else
it.insert(++idx,nit);

while(idx<it.size()-1)
if (it[idx+1].en<=it[idx].en)
it.removeAt(idx+1);
else
break;

if (idx==it.size()-1)
return;

if(it[idx+1].be-1<=it[idx].en) {
it[idx].en=it[idx+1].en;
it.removeAt(idx+1);
}
}

void Prefetcher::rupdate(QHttpResponseHeader resp) {
setsize(resp);
char* dest=values.data();
dest+=spos;
Interval nit;
nit.be=spos;
spos+=http->read(dest,http->bytesAvailable());
nit.en=spos-1;
qDebug() << "nit:"<< nit.be << "-" << nit.en;
addNewInterval(nit);

for(int i=0;i<it.size();i++)
if((spos>=it[i].be)&&(spos<=it[i].en)) {
rmove(it[i].en+1);
return;
}
loop->exit();
emit readyRead();
}

void Prefetcher::rmove(int npos) {
qDebug() << "rmove";
if (http->hasPendingRequests())
http->closeConnection();
buffer.clear();
spos=npos;
int i;
for(i=0;i<it.size();i++)
if ((it[i].be>=spos)&&(it[i].en<=spos))
spos=it[i].en+1;

QHttpRequestHeader hdr("GET",target.path());
hdr.setValue("GET",target.path());
hdr.setValue("Host",target.host());
QString range("bytes=");
range+=QString::number(spos)+"-";
int rightpoint =-1;
for(i=0;i<it.size();i++)
if(spos>it[i].en) {
if (i<it.size()-1)
rightpoint=it[i+1].be-1;
else
rightpoint=-1;
}
if (rightpoint!=-1)
range+=QString::number(rightpoint);
hdr.setValue("Range",range);
http->request(hdr);
loop->exit();
}

void Prefetcher::setsize(QHttpResponseHeader rhead) {
if (rhead.value("Content-Range")!="") {
if (sz==0)
sz=rhead.value("Content-Range").mid(rhead.value("Content-Range").lastIndexOf("/")+1).toInt();
} else if (rhead.value("Content-Length")!="") {
if (sz==0)
sz = rhead.value("Content-Length").toInt();
}
if (values.size()!=sz) {
qDebug() << "resize" << sz << "-" << values.size();
values.resize(sz);
}
loop->exit();
}

Создаётся и юзается вот так:
Код:
	prfch = new Prefetcher(this);
prfch->setSource(path);
media->setCurrentSource(Phonon::MediaSource(prfch));


Название: Re: MediaSource из QIODevice
Отправлено: Dendy от Январь 26, 2009, 22:21
Невооружённым глазом видно, что у вас нереализовано множество обязательных методов из QIODevice. Не нужно вызывать базовый метод, он ровным счётом ничего не значит. Читайте документацию по всем методам и реализуйте их.


Название: Re: MediaSource из QIODevice
Отправлено: Laex от Январь 27, 2009, 13:54
Да, мне ещё много что надо дописать в мойм классе, только я непонимаю что именно. В документации сказано:
Цитировать
By subclassing QIODevice, you can provide the same interface to your own I/O devices. Subclasses of QIODevice are only required to implement the protected readData() and writeData() functions. QIODevice uses these functions to implement all its convenience functions, such as getChar(), readLine() and write(). QIODevice also handles access control for you, so you can safely assume that the device is opened in write mode if writeData() is called.
Но readData() и writeData() не вызываеются - ошибка происходит раньше. Вызывается функция reset, но из описания
Цитировать
bool QIODevice::reset ()   [virtual]
Seeks to the start of input for random-access devices. Returns true on success; otherwise returns false (for example, if the device is not open).
Note that when using a QTextStream on a QFile, calling reset() on the QFile will not have the expected result because QTextStream buffers the file. Use the QTextStream::seek() function instead.
See also seek().
я могу понять только то, что мне нужно вернуть тут true(но базовый метод и так это делает).

По описанию класса:
Цитировать
Detailed Description
The QIODevice class is the base interface class of all I/O devices in Qt.
QIODevice provides both a common implementation and an abstract interface for devices that support reading and writing of blocks of data, such as QFile, QBuffer and QTcpSocket. QIODevice is abstract and can not be instantiated, but it is common to use the interface it defines to provide device-independent I/O features. For example, Qt's XML classes operate on a QIODevice pointer, allowing them to be used with various devices (such as files and buffers).
Before accessing the device, open() must be called to set the correct OpenMode (such as ReadOnly or ReadWrite). You can then write to the device with write() or putChar(), and read by calling either read(), readLine(), or readAll(). Call close() when you are done with the device.
QIODevice distinguishes between two types of devices: random-access devices and sequential devices.
Random-access devices support seeking to arbitrary positions using seek(). The current position in the file is available by calling pos(). QFile and QBuffer are examples of random-access devices.
Sequential devices don't support seeking to arbitrary positions. The data must be read in one pass. The functions pos() and size() don't work for sequential devices. QTcpSocket and QProcess are examples of sequential devices.
You can use isSequential() to determine the type of device.
QIODevice emits readyRead() when new data is available for reading; for example, if new data has arrived on the network or if additional data is appended to a file that you are reading from. You can call bytesAvailable() to determine the number of bytes that currently available for reading. It's common to use bytesAvailable() together with the readyRead() signal when programming with asynchronous devices such as QTcpSocket, where fragments of data can arrive at arbitrary points in time. QIODevice emits the bytesWritten() signal every time a payload of data has been written to the device. Use bytesToWrite() to determine the current amount of data waiting to be written.
Certain subclasses of QIODevice, such as QTcpSocket and QProcess, are asynchronous. This means that I/O functions such as write() or read() always return immediately, while communication with the device itself may happen when control goes back to the event loop. QIODevice provides functions that allow you to force these operations to be performed immediately, while blocking the calling thread and without entering the event loop. This allows QIODevice subclasses to be used without an event loop, or in a separate thread:
waitForReadyRead() - This function suspends operation in the calling thread until new data is available for reading.
waitForBytesWritten() - This function suspends operation in the calling thread until one payload of data has been written to the device.
waitFor....() - Subclasses of QIODevice implement blocking functions for device-specific operations. For example, QProcess has a function called waitForStarted() which suspends operation in the calling thread until the process has started.
Calling these functions from the main, GUI thread, may cause your user interface to freeze. Example:
         QProcess gzip;
         gzip.start("gzip", QStringList() << "-c");
         if (!gzip.waitForStarted())
             return false;

         gzip.write("uncompressed data");

         QByteArray compressed;
         while (gzip.waitForReadyRead())
             compressed += gzip.readAll();
By subclassing QIODevice, you can provide the same interface to your own I/O devices. Subclasses of QIODevice are only required to implement the protected readData() and writeData() functions. QIODevice uses these functions to implement all its convenience functions, such as getChar(), readLine() and write(). QIODevice also handles access control for you, so you can safely assume that the device is opened in write mode if writeData() is called.
Some subclasses, such as QFile and QTcpSocket, are implemented using a memory buffer for intermediate storing of data. This reduces the number of required device accessing calls, which are often very slow. Buffering makes functions like getChar() and putChar() fast, as they can operate on the memory buffer instead of directly on the device itself. Certain I/O operations, however, don't work well with a buffer. For example, if several users open the same device and read it character by character, they may end up reading the same data when they meant to read a separate chunk each. For this reason, QIODevice allows you to bypass any buffering by passing the Unbuffered flag to open(). When subclassing QIODevice, remember to bypass any buffer you may use when the device is open in Unbuffered mode.
See also QBuffer, QFile, and QTcpSocket.
Я понял, что обязательно реализовать только readData и writeData. Ну я бы реализовал другие методы, если б они вызывались. Но они же не вызываются из MediaSource и вообще откуда либо(