//
// PT1Tuner.h
//

#ifndef __RY0_DEVICE_PT1_PT1TUNER_H__
#define __RY0_DEVICE_PT1_PT1TUNER_H__

#include <stdint.h>
#include "ry0/device/Tuner.h"
#include "b25/arib_std_b25.h"
#include "b25/b_cas_card.h"

namespace ry0
{
namespace device
{
namespace PT1
{

static const int PAGE_SIZE          = 4096;
static const int PAGE_COUNT         = 47;
static const int PACKET_SIZE        = 188;
static const int VIRTUAL_SIZE       = 4;
static const int VIRTUAL_COUNT      = 16;
static const int LOCK_SIZE          = 4;
static const int BUFFER_PAGE_COUNT  = 511;
static const int BLOCK_COUNT        = 2;
static const int BLOCK_SIZE         = (PAGE_SIZE * BUFFER_PAGE_COUNT / BLOCK_COUNT);

class PT1Core;

class PT1Tuner : public Tuner
{
    friend class PT1Core;

private:
    CRITICAL_SECTION    _cs;
    PT1Core *           _core;
    Listener *          _listener;
    uint32_t            _tuner;
    char                _name[64];
    int                 _channel;
    bool                _recording;
    int                 _recfd;
    bool                _locked;

    // temporary
    SOCKET              _udp;
    struct sockaddr_in  _dst_addr;

    uint32_t    _count;
    uint32_t    _packetCount;
    uint32_t    _packetOffset;
    uint8_t     _buffer[PAGE_SIZE * PAGE_COUNT];

    ARIB_STD_B25 *  _b25;
    B_CAS_CARD *    _bcas;

    PT1Tuner(PT1Core *core, uint32_t tuner, HMODULE multi2_dll);
    ~PT1Tuner();

    void addPacket(uint32_t packet);

public:
    void setListener(Listener *listener);
    const char *name();
    Type type();
    LnbPower lnbPower();
    bool getCnAgc(uint32_t *cn100, uint32_t *agc, uint32_t *maxAgc);
    int channel();
    bool setChannel(int channel);
    bool startRecording(int fd);
    int stopRecording();
    bool isRecording();
    bool lock();
    void unlock();
    bool isLocked();

    // temporary
    bool startStreaming(struct sockaddr_in *);
    void stopStreaming();
    bool isStreaming();

    //
    static int scan(Tuner *tuners[], HMODULE multi2_dll);
};

} // PT1
} // device
} // ry0

#endif // __RY0_DEVICE_PT1_PT1TUNER_H__
