// -*- c++ -*-

/*
 *
 * Copyright (C) 2002 George Staikos <staikos@kde.org>
 * Copyright (C) 2002 Richard Moore <rich@kde.org>
 * Copyright (C) 2004 Dirk Ziegelmeier <dziegel@gmx.de>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Steet, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#ifndef __KDETV_GRABBER_H
#define __KDETV_GRABBER_H

#include <qobject.h>
#include <qthread.h>
#include <qmutex.h>
//Added by qt3to4:
#include <QEvent>

#include "kdetvvideo/kdetvimage.h"

class QVideoStream;
class KdetvImagePool;
class KdetvImageFilter;
class KdetvFormatConversionFilter;
class KdetvImageFilterContext;
class V4LDev;

#define V4LGRABBER_CONTEXT_HISTORY 4

/*
 * The field images need to be "faked" from progessive images.
 * The algorithm is simple, but the last two fields must not be
 * accessed. Depending on the order, the image with buffer may be
 * deleted while it's corresponding fake field image is still queued.
 */
#define V4LGRABBER_HISTORY V4LGRABBER_CONTEXT_HISTORY+2

class V4LGrabber : public QThread
{
public:
	V4LGrabber(QObject *owner, V4LDev *dev, QVideoStream* vs, int gsn);
	virtual ~V4LGrabber();

	virtual void run();
	void stop() { _stop = true; }
	QMutex& mutex() { return _devMtx; }

    int _fieldTime;
    KdetvImage::ImageType _mostRecentField;
    bool _fullFrameRate;
    KdetvImage::ImageFormat _f;
    KdetvImageFilter* _flt;
    KdetvFormatConversionFilter* _fmtConv;

private:
	QObject *_owner;
	V4LDev *_d;
	volatile bool _stop;
	QMutex _devMtx;
	int _errors;
	QVideoStream* _vs; 
	int _gsn;
    KdetvImagePool* _poolWithBuffer;
    KdetvImagePool* _poolWithoutBuffer;
    KdetvImageFilterContext* _ctx;
    KdetvSharedImage* _images[V4LGRABBER_HISTORY];
};

class V4LErrorEvent : public QEvent
{
public:
    V4LErrorEvent(const QString& msg)
        : QEvent(QEvent::User),
          _msg(msg)
    {
    }

    ~V4LErrorEvent()
    {
    }

    QString _msg;
};

struct V4LGrabberLocker
{
    V4LGrabberLocker(V4LGrabber* g)
        : _g(g) 
    {
        if (_g)
            _g->mutex().lock();
    }

    ~V4LGrabberLocker()
    {
        if (_g)
            _g->mutex().unlock();
    }

    V4LGrabber* _g;
};

#endif

