diff -r -u -N -X diff.exclude -x release.19703.0116b -x release.19703.0116c release.19703.0116b/mythtv/libs/libmythtv/cardutil.cpp release.19703.0116c/mythtv/libs/libmythtv/cardutil.cpp
--- mythtv/libs/libmythtv/cardutil.cpp	2008-03-15 23:22:10.000000000 -0500
+++ mythtv/libs/libmythtv/cardutil.cpp	2009-01-17 00:09:11.000000000 -0600
@@ -38,7 +38,7 @@
             .arg(cardidA).arg(cardidB));
 
     MSqlQuery query(MSqlQuery::InitCon());
-    query.prepare("SELECT videodevice, hostname, cardtype "
+    query.prepare("SELECT videodevice, hostname, cardtype, dbox2_port "
                   "FROM capturecard "
                   "WHERE ( (cardid = :CARDID_A) OR "
                   "        (cardid = :CARDID_B) )");
@@ -57,6 +57,7 @@
     const QString vdevice  = query.value(0).toString();
     const QString hostname = query.value(1).toString();
     const QString cardtype = query.value(2).toString();
+    const QString hdhrTuner = query.value(3).toString();
 
     if (!IsTunerSharingCapable(cardtype.upper()))
         return false;
@@ -67,6 +68,8 @@
     bool ret = ((vdevice  == query.value(0).toString()) &&
                 (hostname == query.value(1).toString()) &&
                 (cardtype == query.value(2).toString()));
+    if (cardtype.upper() == "HDHOMERUN")
+        ret = ret && (hdhrTuner == query.value(3).toString());
 
     VERBOSE(VB_RECORD, QString("IsTunerShared(%1,%2) -> %3")
             .arg(cardidA).arg(cardidB).arg(ret));
@@ -417,6 +420,51 @@
     return list;
 }
 
+/** \fn CardUtil::GetCardIDs(const QString&, uint hdhrTuner, QString)
+ *  \brief Returns all cardids of cards that uses the specified
+ *         videodevice, and optionally rawtype and a non-local 
+ *         hostname. The result is ordered from smallest to largest.
+ *  \param videodevice Video device we want card ids for
+ *  \param hdhrTuner   tuner for this card
+ *  \param hostname    Host on which device resides, only
+ *                     required if said host is not the localhost
+ */
+vector<uint> CardUtil::GetCardIDs(const QString &videodevice,
+                                  uint           hdhrTuner,
+                                  QString        hostname)
+{
+    vector<uint> list;
+
+    if (hostname.isEmpty())
+        hostname = gContext->GetHostName();
+
+    MSqlQuery query(MSqlQuery::InitCon());
+    QString qstr = 
+        "SELECT cardid "
+        "FROM capturecard "
+        "WHERE videodevice = :DEVICE AND "
+        "      dbox2_port  = :HDHRTUNER AND "
+        "      hostname    = :HOSTNAME";
+
+    qstr += " ORDER BY cardid";
+
+    query.prepare(qstr);
+
+    query.bindValue(":DEVICE",   videodevice);
+    query.bindValue(":HDHRTUNER",   hdhrTuner);
+    query.bindValue(":HOSTNAME", hostname);
+
+    if (!query.exec())
+        MythContext::DBError("CardUtil::GetCardIDs(videodevice...)", query);
+    else
+    {
+        while (query.next())
+            list.push_back(query.value(0).toUInt());
+    }
+
+    return list;
+}
+
 static uint clone_capturecard(uint src_cardid, uint orig_dst_cardid)
 {
     uint dst_cardid = orig_dst_cardid;
@@ -468,7 +516,8 @@
         "SELECT videodevice,           cardtype,       defaultinput,     "
         "       hostname,              signal_timeout, channel_timeout,  "
         "       dvb_wait_for_seqstart, dvb_on_demand,  dvb_tuning_delay, "
-        "       dvb_diseqc_type,       diseqcid,       dvb_eitscan "
+        "       dvb_diseqc_type,       diseqcid,       dvb_eitscan,      "
+        "       dbox2_port "
         "FROM capturecard "
         "WHERE cardid = :CARDID");
     query.bindValue(":CARDID", src_cardid);
@@ -498,10 +547,12 @@
         "    dvb_tuning_delay      = :V8, "
         "    dvb_diseqc_type       = :V9, "
         "    diseqcid              = :V10,"
-        "    dvb_eitscan           = :V11 "
+        "    dvb_eitscan           = :V11,"
+        "    dbox2_port            = :V12 "
         "WHERE cardid = :CARDID");
     for (uint i = 0; i < 12; i++)
         query2.bindValue(QString(":V%1").arg(i), query.value(i).toString());
+    query2.bindValue(":V12", query.value(12).toUInt());
     query2.bindValue(":CARDID", dst_cardid);
 
     if (!query2.exec())
@@ -1023,7 +1074,13 @@
         uint id = 0;
         for (uint i = 0; !id && (i < 100); i++)
         {
-            name = QString("DVB%1").arg(dev.toUInt());
+            bool ok;
+            name = QString("DVB%1").arg(dev.toUInt(&ok));
+            if (! ok)
+            {
+                uint hdhrTuner = CardUtil::GetHDHRTuner(cardid);
+                name = QString("HDHR%1").arg(hdhrTuner);
+            }
             name += (i) ? QString(":%1").arg(i) : QString("");
             id = CardUtil::CreateInputGroup(name);
         }
diff -r -u -N -X diff.exclude -x release.19703.0116b -x release.19703.0116c release.19703.0116b/mythtv/libs/libmythtv/cardutil.h release.19703.0116c/mythtv/libs/libmythtv/cardutil.h
--- mythtv/libs/libmythtv/cardutil.h	2008-03-15 23:22:10.000000000 -0500
+++ mythtv/libs/libmythtv/cardutil.h	2009-01-17 00:09:11.000000000 -0600
@@ -106,7 +106,7 @@
 
     static bool         IsTunerSharingCapable(const QString &rawtype)
     {
-        return (rawtype == "DVB");
+        return (rawtype == "DVB")   || (rawtype == "HDHOMERUN");
     }
 
     static bool         IsTunerShared(uint cardidA, uint cardidB);
@@ -135,6 +135,10 @@
                                    QString rawtype  = QString::null,
                                    QString hostname = QString::null);
 
+    static vector<uint> GetCardIDs(const QString &videodevice,
+                                   uint           hdhrTuner,
+                                   QString hostname = QString::null);
+
     static bool         IsCardTypePresent(const QString &rawtype,
                                           QString hostname = QString::null);
     static QStringVec   GetVideoDevices(const QString &rawtype,
diff -r -u -N -X diff.exclude -x release.19703.0116b -x release.19703.0116c release.19703.0116b/mythtv/libs/libmythtv/hdhomerun_includes.h release.19703.0116c/mythtv/libs/libmythtv/hdhomerun_includes.h
--- mythtv/libs/libmythtv/hdhomerun_includes.h	1969-12-31 18:00:00.000000000 -0600
+++ mythtv/libs/libmythtv/hdhomerun_includes.h	2009-01-17 00:09:11.000000000 -0600
@@ -0,0 +1,7 @@
+#ifndef __HDHOMERUN_INCLUDES__
+#define __HDHOMERUN_INCLUDES__
+
+#include "hdhomerun/hdhomerun.h"
+
+#endif /* __HDHOMERUN_INCLUDES__ */
+
diff -r -u -N -X diff.exclude -x release.19703.0116b -x release.19703.0116c release.19703.0116b/mythtv/libs/libmythtv/hdhrchannel.cpp release.19703.0116c/mythtv/libs/libmythtv/hdhrchannel.cpp
--- mythtv/libs/libmythtv/hdhrchannel.cpp	2009-01-16 18:31:06.000000000 -0600
+++ mythtv/libs/libmythtv/hdhrchannel.cpp	2009-01-17 00:09:11.000000000 -0600
@@ -26,15 +26,18 @@
 #include "channelutil.h"
 #include "frequencytables.h"
 
+#include "hdhrstreamhandler.h"
+
 #define DEBUG_PID_FILTERS
 
 #define LOC QString("HDHRChan(%1): ").arg(GetDevice())
 #define LOC_ERR QString("HDHRChan(%1), Error: ").arg(GetDevice())
 
 HDHRChannel::HDHRChannel(TVRec *parent, const QString &device, uint tuner)
-    : DTVChannel(parent),       _control_socket(NULL),
+    : DTVChannel(parent),       _stream_handler(NULL),
       _device_id(0),            _device_ip(0),
-      _tuner(tuner),            _lock(true)
+      _tuner(tuner),            _lock(true),
+      tune_lock(true),          hw_lock(true)
 {
     bool valid;
     _device_id = device.toUInt(&valid, 16);
@@ -65,185 +68,57 @@
 
 bool HDHRChannel::Open(void)
 {
+    VERBOSE(VB_CHANNEL, LOC + "Opening HDHR channel");
+
+    QMutexLocker locker(&hw_lock);
+
     if (IsOpen())
         return true;
 
-    if (!FindDevice())
-        return false;
+    _stream_handler = HDHRStreamHandler::Get(_device_id, _tuner, GetDevice());
 
     if (!InitializeInputs())
-        return false;
-
-    return (_device_ip != 0) && Connect();
-}
-
-void HDHRChannel::Close(void)
-{
-    if (_control_socket)
-    {
-        hdhomerun_control_destroy(_control_socket);
-        _control_socket = NULL;
-    }
-}
-
-bool HDHRChannel::EnterPowerSavingMode(void)
-{
-    return QString::null != TunerSet("channel", "none", false);
-}
-
-bool HDHRChannel::FindDevice(void)
-{
-    if (!_device_id)
-        return _device_ip;
-
-    _device_ip = 0;
-
-    /* Discover. */
-    struct hdhomerun_discover_device_t result;
-    int ret = hdhomerun_discover_find_devices_custom(0, HDHOMERUN_DEVICE_TYPE_WILDCARD, _device_id, &result, 1);
-    if (ret < 0)
     {
-        VERBOSE(VB_IMPORTANT, LOC_ERR + "Unable to send discovery request" + ENO);
+        Close();
         return false;
     }
-    if (ret == 0)
-    {
-        VERBOSE(VB_IMPORTANT, LOC_ERR + QString("device not found"));
-        return false;
-    }
-
-    /* Found. */
-    _device_ip = result.ip_addr;
 
-    VERBOSE(VB_IMPORTANT, LOC +
-            QString("device found at address %1.%2.%3.%4")
-            .arg((_device_ip>>24) & 0xFF).arg((_device_ip>>16) & 0xFF)
-            .arg((_device_ip>> 8) & 0xFF).arg((_device_ip>> 0) & 0xFF));
+//  nextInputID = currentInputID;
 
-    return true;
-}
-
-bool HDHRChannel::Connect(void)
-{
-    _control_socket = hdhomerun_control_create(_device_id, _device_ip);
-    if (!_control_socket)
-    {
-        VERBOSE(VB_IMPORTANT, LOC_ERR + "Unable to create control socket");
-        return false;
-    }
-
-    if (hdhomerun_control_get_local_addr(_control_socket) == 0)
-    {
-        VERBOSE(VB_IMPORTANT, LOC_ERR + "Unable to connect to device");
-        return false;
-    }
+    return _stream_handler->Connected();
 
-    VERBOSE(VB_CHANNEL, LOC + "Successfully connected to device");
-    return true;
 }
 
-QString HDHRChannel::DeviceGet(const QString &name, bool report_error_return)
+void HDHRChannel::Close()
 {
-    QMutexLocker locker(&_lock);
-
-    if (!_control_socket)
-    {
-        VERBOSE(VB_IMPORTANT, LOC_ERR + "Get request failed (not connected)");
-        return QString::null;
-    }
+    VERBOSE(VB_CHANNEL, LOC + "Closing HDHR channel");
 
-    char *value = NULL;
-    char *error = NULL;
-    if (hdhomerun_control_get(_control_socket, name, &value, &error) < 0)
-    {
-        VERBOSE(VB_IMPORTANT, LOC_ERR + "Get request failed" + ENO);
-        return QString::null;
-    }
-
-    if (report_error_return && error)
-    {
-        VERBOSE(VB_IMPORTANT, LOC_ERR +
-                QString("DeviceGet(%1): %2").arg(name).arg(error));
+    if (! IsOpen())
+        return; // this caller didn't have it open in the first place..
 
-        return QString::null;
-    }
-
-    return QString(value);
+    HDHRStreamHandler::Return(_stream_handler);
 }
 
-QString HDHRChannel::DeviceSet(const QString &name, const QString &val,
-                               bool report_error_return)
+bool HDHRChannel::EnterPowerSavingMode(void)
 {
-    QMutexLocker locker(&_lock);
-
-    if (!_control_socket)
-    {
-        VERBOSE(VB_IMPORTANT, LOC_ERR + "Set request failed (not connected)");
-        return QString::null;
-    }
-
-    char *value = NULL;
-    char *error = NULL;
-    if (hdhomerun_control_set(_control_socket, name, val, &value, &error) < 0)
-    {
-        VERBOSE(VB_IMPORTANT, LOC_ERR + "Set request failed" + ENO);
-
-        return QString::null;
-    }
-
-    if (report_error_return && error)
-    {
-        VERBOSE(VB_IMPORTANT, LOC_ERR +
-                QString("DeviceSet(%1 %2): %3").arg(name).arg(val).arg(error));
-
-        return QString::null;
-    }
-
-    return QString(value);
+    if ( IsOpen())
+        return _stream_handler->EnterPowerSavingMode();
+    else
+        return true;
 }
 
-QString HDHRChannel::TunerGet(const QString &name, bool report_error_return)
-{
-    return DeviceGet(QString("/tuner%1/%2").arg(_tuner).arg(name),
-                     report_error_return);
-}
 
-QString HDHRChannel::TunerSet(const QString &name, const QString &value,
-                              bool report_error_return)
+bool HDHRChannel::IsOpen(void) const
 {
-    return DeviceSet(QString("/tuner%1/%2").arg(_tuner).arg(name), value,
-                     report_error_return);
+      return (_stream_handler != NULL);
 }
 
-bool HDHRChannel::DeviceSetTarget(unsigned short localPort)
+bool HDHRChannel::Init(QString &inputname, QString &startchannel, bool setchan)
 {
-    if (localPort == 0)
-    {
-        return false;
-    }
-
-    unsigned long localIP = hdhomerun_control_get_local_addr(_control_socket);
-    if (localIP == 0)
-    {
-        return false;
-    }
-
-    QString configValue = QString("%1.%2.%3.%4:%5")
-        .arg((localIP >> 24) & 0xFF).arg((localIP >> 16) & 0xFF)
-        .arg((localIP >>  8) & 0xFF).arg((localIP >>  0) & 0xFF)
-        .arg(localPort);
+    if (setchan && !IsOpen())
+        Open();
 
-    if (!TunerSet("target", configValue))
-    {
-        return false;
-    }
-
-    return true;
-}
-
-bool HDHRChannel::DeviceClearTarget()
-{
-    return TunerSet("target", "0.0.0.0:0");
+    return ChannelBase::Init(inputname, startchannel, setchan);
 }
 
 bool HDHRChannel::SetChannelByString(const QString &channum)
@@ -277,7 +152,6 @@
         return SwitchToInput(inputName, channum);
 
     ClearDTVInfo();
-    _ignore_filters = false;
 
     InputMap::const_iterator it = inputs.find(currentInputID);
     if (it == inputs.end())
@@ -349,7 +223,8 @@
     if (mpeg_prog_num && (GetTuningMode() == "mpeg"))
     {
         QString pnum = QString::number(mpeg_prog_num);
-        _ignore_filters = QString::null != TunerSet("program", pnum, false);
+        //_ignore_filters = _stream_handler->TuneProgram(pnum);
+        _stream_handler->TuneProgram(pnum);
     }
 
     return true;
@@ -398,155 +273,14 @@
             QString("TuneTo(%1,%2)").arg(frequency).arg(modulation));
 
     if (modulation == "8vsb")
-        ok = TunerSet("channel", QString("8vsb:%1").arg(frequency));
+        ok = _stream_handler->TuneChannel(QString("8vsb:%1").arg(frequency));
     else if (modulation == "qam_64")
-        ok = TunerSet("channel", QString("qam64:%1").arg(frequency));
+        ok = _stream_handler->TuneChannel(QString("qam64:%1").arg(frequency));
     else if (modulation == "qam_256")
-        ok = TunerSet("channel", QString("qam256:%1").arg(frequency));
+        ok = _stream_handler->TuneChannel(QString("qam256:%1").arg(frequency));
 
     if (ok)
         SetSIStandard(si_std);
 
     return ok;
 }
-
-bool HDHRChannel::AddPID(uint pid, bool do_update)
-{
-    QMutexLocker locker(&_lock);
-
-    vector<uint>::iterator it;
-    it = lower_bound(_pids.begin(), _pids.end(), pid);
-    if (it != _pids.end() && *it == pid)
-    {
-#ifdef DEBUG_PID_FILTERS
-        VERBOSE(VB_CHANNEL, "AddPID(0x"<<hex<<pid<<dec<<") NOOP");
-#endif // DEBUG_PID_FILTERS
-        return true;
-    }
-
-    _pids.insert(it, pid);
-
-#ifdef DEBUG_PID_FILTERS
-    VERBOSE(VB_CHANNEL, "AddPID(0x"<<hex<<pid<<dec<<")");
-#endif // DEBUG_PID_FILTERS
-
-    if (do_update)
-        return UpdateFilters();
-    return true;
-}
-
-bool HDHRChannel::DelPID(uint pid, bool do_update)
-{
-    QMutexLocker locker(&_lock);
-
-    vector<uint>::iterator it;
-    it = lower_bound(_pids.begin(), _pids.end(), pid);
-    if (it == _pids.end())
-    {
-#ifdef DEBUG_PID_FILTERS
-        VERBOSE(VB_CHANNEL, "DelPID(0x"<<hex<<pid<<dec<<") NOOP");
-#endif // DEBUG_PID_FILTERS
-
-       return true;
-    }
-
-    if (*it == pid)
-    {
-#ifdef DEBUG_PID_FILTERS
-        VERBOSE(VB_CHANNEL, "DelPID(0x"<<hex<<pid<<dec<<") -- found");
-#endif // DEBUG_PID_FILTERS
-        _pids.erase(it);
-    }
-    else
-    {
-#ifdef DEBUG_PID_FILTERS
-        VERBOSE(VB_CHANNEL, "DelPID(0x"<<hex<<pid<<dec<<") -- failed");
-#endif // DEBUG_PID_FILTERS
-    }
-
-    if (do_update)
-        return UpdateFilters();
-    return true;
-}
-
-bool HDHRChannel::DelAllPIDs(void)
-{
-    QMutexLocker locker(&_lock);
-
-#ifdef DEBUG_PID_FILTERS
-    VERBOSE(VB_CHANNEL, "DelAllPID()");
-#endif // DEBUG_PID_FILTERS
-
-    _pids.clear();
-
-    return UpdateFilters();
-}
-
-QString filt_str(uint pid)
-{
-    uint pid0 = (pid / (16*16*16)) % 16;
-    uint pid1 = (pid / (16*16))    % 16;
-    uint pid2 = (pid / (16))        % 16;
-    uint pid3 = pid % 16;
-    return QString("0x%1%2%3%4")
-        .arg(pid0,0,16).arg(pid1,0,16)
-        .arg(pid2,0,16).arg(pid3,0,16);
-}
-
-bool HDHRChannel::UpdateFilters(void)
-{
-    QMutexLocker locker(&_lock);
-
-    QString filter = "";
-
-    vector<uint> range_min;
-    vector<uint> range_max;
-
-    if (_ignore_filters)
-        return true;
-
-    for (uint i = 0; i < _pids.size(); i++)
-    {
-        uint pid_min = _pids[i];
-        uint pid_max  = pid_min;
-        for (uint j = i + 1; j < _pids.size(); j++)
-        {
-            if (pid_max + 1 != _pids[j])
-                break;
-            pid_max++;
-            i++;
-        }
-        range_min.push_back(pid_min);
-        range_max.push_back(pid_max);
-    }
-
-    if (range_min.size() > 16)
-    {
-        range_min.resize(16);
-        uint pid_max = range_max.back();
-        range_max.resize(15);
-        range_max.push_back(pid_max);
-    }
-
-    for (uint i = 0; i < range_min.size(); i++)
-    {
-        filter += filt_str(range_min[i]);
-        if (range_min[i] != range_max[i])
-            filter += QString("-%1").arg(filt_str(range_max[i]));
-        filter += " ";
-    }
-
-    filter = filter.stripWhiteSpace();
-
-    QString new_filter = TunerSet("filter", filter);
-
-#ifdef DEBUG_PID_FILTERS
-    QString msg = QString("Filter: '%1'").arg(filter);
-    if (filter != new_filter)
-        msg += QString("\n\t\t\t\t'%2'").arg(new_filter);
-
-    VERBOSE(VB_CHANNEL, msg);
-#endif // DEBUG_PID_FILTERS
-
-    return filter == new_filter;
-}
diff -r -u -N -X diff.exclude -x release.19703.0116b -x release.19703.0116c release.19703.0116b/mythtv/libs/libmythtv/hdhrchannel.h release.19703.0116c/mythtv/libs/libmythtv/hdhrchannel.h
--- mythtv/libs/libmythtv/hdhrchannel.h	2008-03-15 23:22:10.000000000 -0500
+++ mythtv/libs/libmythtv/hdhrchannel.h	2009-01-17 00:09:11.000000000 -0600
@@ -15,13 +15,17 @@
 
 // HDHomeRun headers
 #ifdef USING_HDHOMERUN
-#include "hdhomerun/hdhomerun.h"
+#include "hdhomerun_includes.h"
 #else
 struct hdhomerun_control_sock_t { int dummy; };
 #endif
 
 typedef struct hdhomerun_control_sock_t hdhr_socket_t;
 
+class HDHRChannel;
+class HDHRStreamHandler;
+class ProgramMapTable;
+
 class HDHRChannel : public DTVChannel
 {
     friend class HDHRSignalMonitor;
@@ -35,52 +39,40 @@
     void Close(void);
     bool EnterPowerSavingMode(void);
 
+    bool Init(QString &inputname, QString &startchannel, bool setchan);
+
     // Sets
+    void SetPMT(const ProgramMapTable*) {};
     bool SetChannelByString(const QString &chan);
 
     // Gets
-    bool IsOpen(void) const { return (_control_socket != NULL); }
+    bool IsOpen(void) const;
     QString GetDevice(void) const
         { return QString("%1/%2").arg(_device_id, 8, 16).arg(_tuner); }
+    uint GetDeviceId(void) const { return _device_id; }
+    uint GetTuner(void) const { return _tuner; }
     vector<uint> GetPIDs(void) const
         { QMutexLocker locker(&_lock); return _pids; }
     QString GetSIStandard(void) const { return "atsc"; }
 
-    // Commands
-    bool AddPID(uint pid, bool do_update = true);
-    bool DelPID(uint pid, bool do_update = true);
-    bool DelAllPIDs(void);
-    bool UpdateFilters(void);
-
     // ATSC scanning stuff
     bool TuneMultiplex(uint mplexid, QString inputname);
     bool Tune(const DTVMultiplex &tuning, QString inputname);
 
   private:
-    bool FindDevice(void);
-    bool Connect(void);
     bool Tune(uint frequency, QString inputname,
               QString modulation, QString si_std);
 
-    bool DeviceSetTarget(unsigned short localPort);
-    bool DeviceClearTarget(void);
-
-    QString DeviceGet(const QString &name, bool report_error_return = true);
-    QString DeviceSet(const QString &name, const QString &value,
-                      bool report_error_return = true);
-
-    QString TunerGet(const QString &name, bool report_error_return = true);
-    QString TunerSet(const QString &name, const QString &value,
-                     bool report_error_return = true);
-
   private:
-    hdhr_socket_t  *_control_socket;
+    HDHRStreamHandler *_stream_handler;
+
     uint            _device_id;
     uint            _device_ip;
     uint            _tuner;
-    bool            _ignore_filters;
     vector<uint>    _pids;
     mutable QMutex  _lock;
+    mutable QMutex  tune_lock;
+    mutable QMutex  hw_lock;
 };
 
 #endif
diff -r -u -N -X diff.exclude -x release.19703.0116b -x release.19703.0116c release.19703.0116b/mythtv/libs/libmythtv/hdhrrecorder.cpp release.19703.0116c/mythtv/libs/libmythtv/hdhrrecorder.cpp
--- mythtv/libs/libmythtv/hdhrrecorder.cpp	2009-01-17 00:28:49.000000000 -0600
+++ mythtv/libs/libmythtv/hdhrrecorder.cpp	2009-01-17 00:09:11.000000000 -0600
@@ -23,23 +23,31 @@
 
 // MythTV includes
 #include "RingBuffer.h"
-#include "hdhrchannel.h"
-#include "hdhrrecorder.h"
 #include "atsctables.h"
 #include "atscstreamdata.h"
 #include "eithelper.h"
 #include "tv_rec.h"
 
+// MythTV HDHR includes
+#include "hdhrchannel.h"
+#include "hdhrrecorder.h"
+#include "hdhrstreamhandler.h"
+
 #define LOC QString("HDHRRec(%1): ").arg(tvrec->GetCaptureCardNum())
+#define LOC_WARN QString("HDHRRec(%1), Warning: ") \
+                    .arg(tvrec->GetCaptureCardNum())
 #define LOC_ERR QString("HDHRRec(%1), Error: ") \
                     .arg(tvrec->GetCaptureCardNum())
 
 HDHRRecorder::HDHRRecorder(TVRec *rec, HDHRChannel *channel)
     : DTVRecorder(rec),
-      _channel(channel),        _video_socket(NULL),
+      _channel(channel),
+      _stream_handler(NULL),
       _stream_data(NULL),
-      _input_pat(NULL),         _input_pmt(NULL),
-      _reset_pid_filters(false),_pid_lock(true)
+      _pid_lock(true),
+      _input_pat(NULL),
+      _input_pmt(NULL),
+      _has_no_av(false)
 {
 }
 
@@ -90,74 +98,44 @@
     // HACK -- end
 }
 
+bool HDHRRecorder::IsOpen(void) {
+    return (_stream_handler != NULL);
+}
+
 bool HDHRRecorder::Open(void)
 {
     VERBOSE(VB_RECORD, LOC + "Open()");
-    if (_video_socket)
+    if (IsOpen())
     {
         VERBOSE(VB_RECORD, LOC + "Card already open (recorder)");
         return true;
     }
 
-    /* Calculate buffer size */
-    uint buffersize = gContext->GetNumSetting(
-        "HDRingbufferSize", 50 * TSPacket::SIZE) * 1024;
-    buffersize /= VIDEO_DATA_PACKET_SIZE;
-    buffersize *= VIDEO_DATA_PACKET_SIZE;
+    bzero(_stream_id,  sizeof(_stream_id));
+    bzero(_pid_status, sizeof(_pid_status));
+    memset(_continuity_counter, 0xff, sizeof(_continuity_counter));
 
-    // Buffer should be at least about 1MB..
-    buffersize = max(49 * TSPacket::SIZE * 128, buffersize);
+    _stream_handler = HDHRStreamHandler::Get(_channel->GetDeviceId(), _channel->GetTuner(), _channel->GetDevice());
 
-    /* Create TS socket. */
-    _video_socket = hdhomerun_video_create(0, buffersize);
-    if (!_video_socket)
-    {
-        VERBOSE(VB_IMPORTANT, LOC + "Open() failed to open socket");
-        return false;
-    }
+    VERBOSE(VB_RECORD, LOC + "HDHR opened successfully");
 
-    /* Success. */
     return true;
 }
 
-/** \fn HDHRRecorder::StartData(void)
- *  \brief Configure device to send video.
- */
-bool HDHRRecorder::StartData(void)
-{
-    VERBOSE(VB_RECORD, LOC + "StartData()");
-    uint localPort = hdhomerun_video_get_local_port(_video_socket);
-    return _channel->DeviceSetTarget(localPort);
-}
-
 void HDHRRecorder::Close(void)
 {
-    VERBOSE(VB_RECORD, LOC + "Close()");
-    if (_video_socket)
+    VERBOSE(VB_RECORD, LOC + "Close() - Begin");
+
+    if (IsOpen())
     {
-        hdhomerun_video_destroy(_video_socket);
-        _video_socket = NULL;
+        HDHRStreamHandler::Return(_stream_handler); 
     }
-}
-
-void HDHRRecorder::ProcessTSData(const uint8_t *buffer, int len)
-{
-    QMutexLocker locker(&_pid_lock);
-    const uint8_t *data = buffer;
-    const uint8_t *end = buffer + len;
-
-    while (data + 188 <= end)
+    else
     {
-        if (data[0] != 0x47)
-        {
-            return;
-        }
-
-        const TSPacket *tspacket = reinterpret_cast<const TSPacket*>(data);
-        ProcessTSPacket(*tspacket);
-
-        data += 188;
+        VERBOSE(VB_IMPORTANT,QString( LOC + " Trying to Close HDHR But it's not open"));
     }
+
+    VERBOSE(VB_RECORD, LOC + "Close() - End");
 }
 
 void HDHRRecorder::SetStreamData(MPEGStreamData *data)
@@ -216,8 +194,6 @@
     ProgramAssociationTable *oldpat = _input_pat;
     _input_pat = new ProgramAssociationTable(*_pat);
     delete oldpat;
-
-    _reset_pid_filters = true;
 }
 
 void HDHRRecorder::HandlePMT(uint progNum, const ProgramMapTable *_pmt)
@@ -229,9 +205,19 @@
         VERBOSE(VB_RECORD, LOC + "SetPMT("<<progNum<<")");
         ProgramMapTable *oldpmt = _input_pmt;
         _input_pmt = new ProgramMapTable(*_pmt);
-        delete oldpmt;
 
-        _reset_pid_filters = true;
+        QString sistandard = _channel->GetSIStandard();
+
+        bool has_no_av = true;
+        for (uint i = 0; i < _input_pmt->StreamCount() && has_no_av; i++)
+        {
+            has_no_av &= !_input_pmt->IsVideo(i, sistandard);
+            has_no_av &= !_input_pmt->IsAudio(i, sistandard);
+        }
+        _has_no_av = has_no_av;
+
+        _channel->SetPMT(_input_pmt);
+        delete oldpmt;
     }
 }
 
@@ -242,12 +228,22 @@
 
     int next = (pat->tsheader()->ContinuityCounter()+1)&0xf;
     pat->tsheader()->SetContinuityCounter(next);
-    BufferedWrite(*(reinterpret_cast<TSPacket*>(pat->tsheader())));
+    DTVRecorder::BufferedWrite(*(reinterpret_cast<TSPacket*>(pat->tsheader())));
 }
 
 void HDHRRecorder::HandleSingleProgramPMT(ProgramMapTable *pmt)
 {
     if (!pmt)
+    {
+        VERBOSE(VB_RECORD, LOC + "HandleSingleProgramPMT(NULL)");
+        return;
+    }
+
+    // collect stream types for H.264 (MPEG-4 AVC) keyframe detection
+    for (uint i = 0; i < pmt->StreamCount(); i++)
+        _stream_id[pmt->StreamPID(i)] = pmt->StreamType(i);
+
+    if (!ringBuffer)
         return;
 
     unsigned char buf[8 * 1024];
@@ -255,8 +251,23 @@
     pmt->tsheader()->SetContinuityCounter(next_cc);
     uint size = pmt->WriteAsTSPackets(buf, next_cc);
 
+    uint posA[2] = { ringBuffer->GetWritePosition(), _payload_buffer.size() };
+
     for (uint i = 0; i < size ; i += TSPacket::SIZE)
         DTVRecorder::BufferedWrite(*(reinterpret_cast<TSPacket*>(&buf[i])));
+
+    uint posB[2] = { ringBuffer->GetWritePosition(), _payload_buffer.size() };
+
+    if (posB[0] + posB[1] * TSPacket::SIZE >
+        posA[0] + posA[1] * TSPacket::SIZE)
+    {
+        VERBOSE(VB_RECORD, LOC + "Wrote PMT @"
+                << posA[0] << " + " << (posA[1] * TSPacket::SIZE));
+    }
+    else
+    {
+        VERBOSE(VB_RECORD, LOC + "Saw PMT but did not write to disk yet");
+    }
 }
 
 /** \fn HDHRRecorder::HandleMGT(const MasterGuideTable*)
@@ -276,46 +287,75 @@
 }
 */
 
+bool HDHRRecorder::ProcessVideoTSPacket(const TSPacket &tspacket)
+{
+    uint streamType = _stream_id[tspacket.PID()];
+
+    // Check for keyframes and count frames
+    if (streamType == StreamID::H264Video)
+    {
+        _buffer_packets = !FindH264Keyframes(&tspacket);
+        if (!_seen_sps)
+            return true;
+    }
+    else
+    {
+        _buffer_packets = !FindMPEG2Keyframes(&tspacket);
+    }
+
+    return ProcessAVTSPacket(tspacket);
+}
+
+bool HDHRRecorder::ProcessAudioTSPacket(const TSPacket &tspacket)
+{
+    _buffer_packets = !FindAudioKeyframes(&tspacket);
+    return ProcessAVTSPacket(tspacket);
+}
+
+/// Common code for processing either audio or video packets
+bool HDHRRecorder::ProcessAVTSPacket(const TSPacket &tspacket)
+{
+    const uint pid = tspacket.PID();
+    // Sync recording start to first keyframe
+    if (_wait_for_keyframe_option && _first_keyframe < 0)
+        return true;
+
+    // Sync streams to the first Payload Unit Start Indicator
+    // _after_ first keyframe iff _wait_for_keyframe_option is true
+    if (!(_pid_status[pid] & kPayloadStartSeen) && tspacket.HasPayload())
+    {
+        if (!tspacket.PayloadStart())
+            return true; // not payload start - drop packet
+
+        VERBOSE(VB_RECORD,
+                QString("PID 0x%1 Found Payload Start").arg(pid,0,16));
+
+        _pid_status[pid] |= kPayloadStartSeen;
+    }
+
+    BufferedWrite(tspacket);
+
+    return true;
+}
+
 bool HDHRRecorder::ProcessTSPacket(const TSPacket& tspacket)
 {
-    bool ok = !tspacket.TransportError();
-    if (ok && !tspacket.ScramplingControl())
+    // Only create fake keyframe[s] if there are no audio/video streams
+    if (_input_pmt && _has_no_av)
     {
-        if (tspacket.HasAdaptationField())
-            GetStreamData()->HandleAdaptationFieldControl(&tspacket);
-        if (tspacket.HasPayload())
-        {
-            const unsigned int lpid = tspacket.PID();
+        _buffer_packets = !FindOtherKeyframes(&tspacket);
+    }
+    else
+    {
+        // There are audio/video streams. Only write the packet
+        // if audio/video key-frames have been found
+        if (_wait_for_keyframe_option && _first_keyframe < 0)
+            return true;
 
-            if ((GetStreamData()->VideoPIDSingleProgram() > 0x1fff) &&
-                _wait_for_keyframe_option)
-            {
-                _wait_for_keyframe_option = false;
-            }
-
-            // Pass or reject frames based on PID, and parse info from them
-            if (lpid == GetStreamData()->VideoPIDSingleProgram())
-            {
-                //cerr<<"v";
-                _buffer_packets = !FindMPEG2Keyframes(&tspacket);
-                BufferedWrite(tspacket);
-            }
-            else if (GetStreamData()->IsAudioPID(lpid))
-            {
-                //cerr<<"a";
-                _buffer_packets = !FindAudioKeyframes(&tspacket);
-                BufferedWrite(tspacket);
-            }
-            else if (GetStreamData()->IsListeningPID(lpid))
-            {
-                //cerr<<"t";
-                GetStreamData()->HandleTSTables(&tspacket);
-            }
-            else if (GetStreamData()->IsWritingPID(lpid))
-                BufferedWrite(tspacket);
-        }
+        _buffer_packets = true;
     }
-    return ok;
+
+    BufferedWrite(tspacket);
 }
 
 void HDHRRecorder::StartRecording(void)
@@ -333,54 +373,47 @@
     _request_recording = true;
     _recording = true;
 
-    if (!StartData())
-    {
-        VERBOSE(VB_IMPORTANT, LOC_ERR + "Starting recording "
-                "(set target failed). Aborting.");
-        Close();
-        _error = true;
-        VERBOSE(VB_RECORD, LOC + "StartRecording -- end 2");
-        return;
-    }
-
-    hdhomerun_video_flush(_video_socket);
+    // Make sure the first things in the file are a PAT & PMT
+    bool tmp = _wait_for_keyframe_option;
+    _wait_for_keyframe_option = false;
+    HandleSingleProgramPAT(_stream_data->PATSingleProgram());
+    HandleSingleProgramPMT(_stream_data->PMTSingleProgram());
+    _wait_for_keyframe_option = tmp;
+
+    _stream_data->AddAVListener(this);
+    _stream_data->AddWritingListener(this);
+    _stream_handler->AddListener(_stream_data);
+    
     while (_request_recording && !_error)
     {
+        usleep(50000);
+
         if (PauseAndWait())
             continue;
 
-        if (_stream_data)
+        if (!_input_pmt)
         {
-            QMutexLocker read_lock(&_pid_lock);
-            _reset_pid_filters |= _stream_data->HasEITPIDChanges(_eit_pids);
+            VERBOSE(VB_GENERAL, LOC_WARN +
+                    "Recording will not commence until a PMT is set.");
+            usleep(5000);
+            continue;
         }
 
-        if (_reset_pid_filters)
+        if (!_stream_handler->IsRunning())
         {
-            _reset_pid_filters = false;
-            VERBOSE(VB_RECORD, LOC + "Resetting Demux Filters");
-            AdjustFilters();
-        }
+            _error = true;
 
-        size_t read_size = 64 * 1024; // read about 64KB
-        read_size /= VIDEO_DATA_PACKET_SIZE;
-        read_size *= VIDEO_DATA_PACKET_SIZE;
-
-        size_t data_length;
-        unsigned char *data_buffer =
-            hdhomerun_video_recv(_video_socket, read_size, &data_length);
-        if (!data_buffer)
-        {
-            usleep(5000);
-	    continue;
-	}
-
-        ProcessTSData(data_buffer, data_length);
+            VERBOSE(VB_IMPORTANT, LOC_ERR +
+                    "Stream handler died unexpectedly.");
+        }
     }
 
     VERBOSE(VB_RECORD, LOC + "StartRecording -- ending...");
 
-    _channel->DeviceClearTarget();
+    _stream_handler->RemoveListener(_stream_data);
+    _stream_data->RemoveWritingListener(this);
+    _stream_data->RemoveAVListener(this);
+
     Close();
 
     FinishRecording();
@@ -389,104 +422,82 @@
     VERBOSE(VB_RECORD, LOC + "StartRecording -- end");
 }
 
-bool HDHRRecorder::AdjustFilters(void)
+void HDHRRecorder::ResetForNewFile(void)
 {
-    QMutexLocker change_lock(&_pid_lock);
+    DTVRecorder::ResetForNewFile();
 
-    if (!_channel)
-    {
-        VERBOSE(VB_IMPORTANT, LOC_ERR + "AdjustFilters() no channel");
-        return false;
-    }
+    bzero(_stream_id,  sizeof(_stream_id));
+    bzero(_pid_status, sizeof(_pid_status));
+    memset(_continuity_counter, 0xff, sizeof(_continuity_counter));
 
-    if (!_input_pat || !_input_pmt)
-    {
-        VERBOSE(VB_IMPORTANT, LOC + "AdjustFilters() no pmt or no pat");
-        return false;
-    }
-
-    uint_vec_t add_pid;
+    // FIXME
+    // Close and re-open ???
+    //Close();
+    //Open();
+}
 
-    add_pid.push_back(MPEG_PAT_PID);
-    _stream_data->AddListeningPID(MPEG_PAT_PID);
+void HDHRRecorder::StopRecording(void)
+{
+    _request_recording = false;
+    while (_recording)
+        usleep(2000);
+}
 
-    for (uint i = 0; i < _input_pat->ProgramCount(); i++)
+bool HDHRRecorder::PauseAndWait(int timeout)
+{
+    if (request_pause)
     {
-        add_pid.push_back(_input_pat->ProgramPID(i));
-        _stream_data->AddListeningPID(_input_pat->ProgramPID(i));
-    }
+        if (!paused)
+        {
+            assert(_stream_handler);
+            assert(_stream_data);
 
-    // Record the streams in the PMT...
-    bool need_pcr_pid = true;
-    for (uint i = 0; i < _input_pmt->StreamCount(); i++)
-    {
-        add_pid.push_back(_input_pmt->StreamPID(i));
-        need_pcr_pid &= (_input_pmt->StreamPID(i) != _input_pmt->PCRPID());
-        _stream_data->AddWritingPID(_input_pmt->StreamPID(i));
-    }
+            _stream_handler->RemoveListener(_stream_data);
 
-    if (need_pcr_pid && (_input_pmt->PCRPID()))
-    {
-        add_pid.push_back(_input_pmt->PCRPID());
-        _stream_data->AddWritingPID(_input_pmt->PCRPID());
+            paused = true;
+            pauseWait.wakeAll();
+            if (tvrec)
+                tvrec->RecorderPaused();
+        }
+        unpauseWait.wait(timeout);
     }
 
-    // Adjust for EIT
-    AdjustEITPIDs();
-    for (uint i = 0; i < _eit_pids.size(); i++)
+    if (!request_pause && paused)
     {
-        add_pid.push_back(_eit_pids[i]);
-        _stream_data->AddListeningPID(_eit_pids[i]);
-    }
+        paused = false;
 
-    // Delete filters for pids we no longer wish to monitor
-    vector<uint>::const_iterator it;
-    vector<uint> pids = _channel->GetPIDs();
-    for (it = pids.begin(); it != pids.end(); ++it)
-    {
-        if (find(add_pid.begin(), add_pid.end(), *it) == add_pid.end())
-        {
-            _stream_data->RemoveListeningPID(*it);
-            _stream_data->RemoveWritingPID(*it);
-            _channel->DelPID(*it, false);
-        }
-    }
+        assert(_stream_handler);
+        assert(_stream_data);
 
-    for (it = add_pid.begin(); it != add_pid.end(); ++it)
-        _channel->AddPID(*it, false);
-
-    _channel->UpdateFilters();
+        _stream_handler->AddListener(_stream_data);
+    }
 
-    return add_pid.size();
+    return paused;
 }
 
-/** \fn HDHRRecorder::AdjustEITPIDs(void)
- *  \brief Adjusts EIT PID monitoring to monitor the right number of EIT PIDs.
- */
-bool HDHRRecorder::AdjustEITPIDs(void)
+void HDHRRecorder::BufferedWrite(const TSPacket &tspacket)
 {
-    bool changes = false;
-    uint_vec_t add, del;
-
-    QMutexLocker change_lock(&_pid_lock);
-
-    if (GetStreamData()->HasEITPIDChanges(_eit_pids))
-        changes = GetStreamData()->GetEITPIDChanges(_eit_pids, add, del);
+    // Care must be taken to make sure that the packet actually gets written
+    // as the decision to actually write it has already been made
 
-    if (!changes)
-        return false;
-
-    for (uint i = 0; i < del.size(); i++)
+    // Do we have to buffer the packet for exact keyframe detection?
+    if (_buffer_packets)
     {
-        uint_vec_t::iterator it;
-        it = find(_eit_pids.begin(), _eit_pids.end(), del[i]);
-        if (it != _eit_pids.end())
-            _eit_pids.erase(it);
+        int idx = _payload_buffer.size();
+        _payload_buffer.resize(idx + TSPacket::SIZE);
+        memcpy(&_payload_buffer[idx], tspacket.data(), TSPacket::SIZE);
+        return;
     }
 
-    for (uint i = 0; i < add.size(); i++)
-        _eit_pids.push_back(add[i]);
-
-    return true;
+    // We are free to write the packet, but if we have buffered packet[s]
+    // we have to write them first...
+    if (!_payload_buffer.empty())
+    {
+        if (ringBuffer)
+            ringBuffer->Write(&_payload_buffer[0], _payload_buffer.size());
+        _payload_buffer.clear();
+    }
+    if (ringBuffer)
+        ringBuffer->Write(tspacket.data(), TSPacket::SIZE);
 }
 
diff -r -u -N -X diff.exclude -x release.19703.0116b -x release.19703.0116c release.19703.0116b/mythtv/libs/libmythtv/hdhrrecorder.h release.19703.0116c/mythtv/libs/libmythtv/hdhrrecorder.h
--- mythtv/libs/libmythtv/hdhrrecorder.h	2008-03-15 23:22:10.000000000 -0500
+++ mythtv/libs/libmythtv/hdhrrecorder.h	2009-01-17 00:09:11.000000000 -0600
@@ -14,12 +14,17 @@
 
 class HDHRChannel;
 class ProgramMapTable;
+class MPEGStreamData;
+class HDHRStreamHandler;
+
 
 typedef vector<uint>        uint_vec_t;
 
 class HDHRRecorder : public DTVRecorder,
                      public MPEGStreamListener,
-                     public MPEGSingleProgramStreamListener
+                     public MPEGSingleProgramStreamListener,
+                     public TSPacketListener,
+                     public TSPacketListenerAV
 {
     friend class ATSCStreamData;
 
@@ -33,10 +38,12 @@
                                const QString &vbidev);
 
     bool Open(void);
-    bool StartData(void);
+    bool IsOpen(void);
     void Close(void);
 
     void StartRecording(void);
+    void ResetForNewFile(void);
+    void StopRecording(void);
 
     void SetStreamData(MPEGStreamData*);
     MPEGStreamData *GetStreamData(void) { return _stream_data; }
@@ -59,24 +66,42 @@
     void HandleVCT(uint, const VirtualChannelTable*) {}
     */
 
-  private:
-    bool AdjustFilters(void);
-    bool AdjustEITPIDs(void);
+    // TSPacketListenerAV
+    bool ProcessVideoTSPacket(const TSPacket& tspacket);
+    bool ProcessAudioTSPacket(const TSPacket& tspacket);
+
+    // Common audio/visual processing
+    bool ProcessAVTSPacket(const TSPacket &tspacket);
 
-    void ProcessTSData(const unsigned char *buffer, int len);
     bool ProcessTSPacket(const TSPacket& tspacket);
+
+    void BufferedWrite(const TSPacket &tspacket);
+  private:
     void TeardownAll(void);
+
+    void ReaderPaused(int fd);
+    bool PauseAndWait(int timeout = 100);
     
   private:
     HDHRChannel                   *_channel;
-    struct hdhomerun_video_sock_t *_video_socket;
+    HDHRStreamHandler             *_stream_handler;
     MPEGStreamData                *_stream_data;
 
+    mutable QMutex                 _pid_lock;
     ProgramAssociationTable       *_input_pat;
     ProgramMapTable               *_input_pmt;
-    bool                           _reset_pid_filters;
-    uint_vec_t                     _eit_pids;
-    mutable QMutex                 _pid_lock;
+    bool                           _has_no_av;
+
+    unsigned char   _stream_id[0x1fff];
+    unsigned char   _pid_status[0x1fff];
+    unsigned char   _continuity_counter[0x1fff];
+
+    // Constants
+    static const int TSPACKETS_BETWEEN_PSIP_SYNC;
+    static const int POLL_INTERVAL;
+    static const int POLL_WARNING_TIMEOUT;
+
+    static const unsigned char kPayloadStartSeen = 0x2;
 };
 
 #endif
diff -r -u -N -X diff.exclude -x release.19703.0116b -x release.19703.0116c release.19703.0116b/mythtv/libs/libmythtv/hdhrsignalmonitor.cpp release.19703.0116c/mythtv/libs/libmythtv/hdhrsignalmonitor.cpp
--- mythtv/libs/libmythtv/hdhrsignalmonitor.cpp	2008-03-15 23:22:10.000000000 -0500
+++ mythtv/libs/libmythtv/hdhrsignalmonitor.cpp	2009-01-17 00:09:11.000000000 -0600
@@ -18,6 +18,7 @@
 
 #include "hdhrchannel.h"
 #include "hdhrrecorder.h"
+#include "hdhrstreamhandler.h"
 
 #define LOC QString("HDHRSM(%1): ").arg(channel->GetDevice())
 #define LOC_ERR QString("HDHRSM(%1), Error: ").arg(channel->GetDevice())
@@ -41,15 +42,17 @@
                                      HDHRChannel* _channel,
                                      uint64_t _flags, const char *_name)
     : DTVSignalMonitor(db_cardnum, _channel, _flags, _name),
-      dtvMonitorRunning(false)
+      streamHandlerStarted(false),
+      streamHandler(NULL)
+
 {
     VERBOSE(VB_CHANNEL, LOC + "ctor");
 
-    _channel->DelAllPIDs();
-
     signalStrength.SetThreshold(45);
 
     AddFlags(kDTVSigMon_WaitForSig);
+
+    streamHandler = HDHRStreamHandler::Get(_channel->GetDeviceId(), _channel->GetTuner(), _channel->GetDevice());
 }
 
 /** \fn HDHRSignalMonitor::~HDHRSignalMonitor()
@@ -59,6 +62,7 @@
 {
     VERBOSE(VB_CHANNEL, LOC + "dtor");
     Stop();
+    HDHRStreamHandler::Return(streamHandler);
 }
 
 void HDHRSignalMonitor::deleteLater(void)
@@ -75,118 +79,17 @@
 {
     VERBOSE(VB_CHANNEL, LOC + "Stop() -- begin");
     SignalMonitor::Stop();
-    if (dtvMonitorRunning)
-    {
-        dtvMonitorRunning = false;
-        pthread_join(table_monitor_thread, NULL);
-    }
-    VERBOSE(VB_CHANNEL, LOC + "Stop() -- end");
-}
+    if (GetStreamData())
+        streamHandler->RemoveListener(GetStreamData());
+    streamHandlerStarted = false;
+    streamHandler->SetRetuneAllowed(false, NULL, NULL);
 
-void *HDHRSignalMonitor::TableMonitorThread(void *param)
-{
-    HDHRSignalMonitor *mon = (HDHRSignalMonitor*) param;
-    mon->RunTableMonitor();
-    return NULL;
-}
-
-bool HDHRSignalMonitor::UpdateFiltersFromStreamData(void)
-{
-    vector<int> add_pids;
-    vector<int> del_pids;
-
-    if (!GetStreamData())
-        return false;
-
-    UpdateListeningForEIT();
-
-    const pid_map_t &listening = GetStreamData()->ListeningPIDs();
-
-    // PIDs that need to be added..
-    pid_map_t::const_iterator lit = listening.constBegin();
-    for (; lit != listening.constEnd(); ++lit)
-        if (lit.data() && (filters.find(lit.key()) == filters.end()))
-            add_pids.push_back(lit.key());
-
-    // PIDs that need to be removed..
-    FilterMap::const_iterator fit = filters.constBegin();
-    for (; fit != filters.constEnd(); ++fit)
-        if (listening.find(fit.key()) == listening.end())
-            del_pids.push_back(fit.key());
-
-    HDHRChannel *hdhr = dynamic_cast<HDHRChannel*>(channel);
-    // Remove PIDs
-    bool ok = true;
-    vector<int>::iterator dit = del_pids.begin();
-    for (; dit != del_pids.end(); ++dit)
-    {
-        ok &= hdhr->DelPID(*dit);
-        filters.erase(filters.find(*dit));
-    }
-
-    // Add PIDs
-    vector<int>::iterator ait = add_pids.begin();
-    for (; ait != add_pids.end(); ++ait)
-    {
-        ok &= hdhr->AddPID(*ait);
-        filters[*ait] = 1;
-    }
-
-    return ok;
+    VERBOSE(VB_CHANNEL, LOC + "Stop() -- end");
 }
 
-void HDHRSignalMonitor::RunTableMonitor(void)
+HDHRChannel *HDHRSignalMonitor::GetHDHRChannel(void)
 {
-    dtvMonitorRunning = true;
-
-    struct hdhomerun_video_sock_t *_video_socket;
-    _video_socket = hdhomerun_video_create(0, VIDEO_DATA_BUFFER_SIZE_1S);
-    if (!_video_socket)
-    {
-        VERBOSE(VB_IMPORTANT, LOC_ERR + "Failed to get video socket");
-        return;
-    }
-
-    HDHRChannel *hdrc = dynamic_cast<HDHRChannel*>(channel);
-    uint localPort = hdhomerun_video_get_local_port(_video_socket);
-    if (!hdrc->DeviceSetTarget(localPort))
-    {
-        hdhomerun_video_destroy(_video_socket);
-        VERBOSE(VB_IMPORTANT, LOC_ERR + "Failed to set target");
-        return;
-    }
-
-    VERBOSE(VB_CHANNEL, LOC + "RunTableMonitor(): " +
-            QString("begin (# of pids %1)")
-            .arg(GetStreamData()->ListeningPIDs().size()));
-
-    while (dtvMonitorRunning && GetStreamData())
-    {
-        UpdateFiltersFromStreamData();
-
-        size_t data_length;
-        unsigned char *data_buffer =
-            hdhomerun_video_recv(_video_socket,
-                                         VIDEO_DATA_BUFFER_SIZE_1S / 5,
-                                         &data_length);
-
-        if (data_buffer)
-        {
-            GetStreamData()->ProcessData(data_buffer, data_length);
-            continue;
-        }
-
-        usleep(2500);
-    }
-
-    hdrc->DeviceClearTarget();
-    hdhomerun_video_destroy(_video_socket);
-
-    VERBOSE(VB_CHANNEL, LOC + "RunTableMonitor(): -- shutdown");
-
-    // TODO teardown PID filters here
-
-    VERBOSE(VB_CHANNEL, LOC + "RunTableMonitor(): -- end");
+    return dynamic_cast<HDHRChannel*>(channel);
 }
 
 /** \fn HDHRSignalMonitor::UpdateValues()
@@ -204,7 +107,7 @@
     if (!running || exit)
         return;
 
-    if (dtvMonitorRunning)
+    if (streamHandlerStarted)
     {
         EmitHDHRSignals();
         if (IsAllGood())
@@ -215,7 +118,7 @@
         return;
     }
 
-    QString msg = ((HDHRChannel*)channel)->TunerGet("status");
+    QString msg = streamHandler->GetTunerStatus();
     //ss  = signal strength,        [0,100]
     //snq = signal to noise quality [0,100]
     //seq = signal error quality    [0,100]
@@ -253,17 +156,8 @@
                    kDTVSigMon_WaitForMGT | kDTVSigMon_WaitForVCT |
                    kDTVSigMon_WaitForNIT | kDTVSigMon_WaitForSDT))
     {
-        pthread_create(&table_monitor_thread, NULL,
-                       TableMonitorThread, this);
-
-        VERBOSE(VB_CHANNEL, LOC + "UpdateValues() -- "
-                "Waiting for table monitor to start");
-
-        while (!dtvMonitorRunning)
-            usleep(50);
-
-        VERBOSE(VB_CHANNEL, LOC + "UpdateValues() -- "
-                "Table monitor started");
+        streamHandler->AddListener(GetStreamData());
+        streamHandlerStarted = true;
     }
 
     update_done = true;
diff -r -u -N -X diff.exclude -x release.19703.0116b -x release.19703.0116c release.19703.0116b/mythtv/libs/libmythtv/hdhrsignalmonitor.h release.19703.0116c/mythtv/libs/libmythtv/hdhrsignalmonitor.h
--- mythtv/libs/libmythtv/hdhrsignalmonitor.h	2008-03-15 23:22:10.000000000 -0500
+++ mythtv/libs/libmythtv/hdhrsignalmonitor.h	2009-01-17 00:09:11.000000000 -0600
@@ -7,6 +7,7 @@
 #include "qstringlist.h"
 
 class HDHRChannel;
+class HDHRStreamHandler;
 
 typedef QMap<uint,int> FilterMap;
 
@@ -21,8 +22,6 @@
 
     void Stop(void);
 
-    bool UpdateFiltersFromStreamData(void);
-
   public slots:
     void deleteLater(void);
 
@@ -33,16 +32,15 @@
     virtual void UpdateValues(void);
     void EmitHDHRSignals(void);
 
-    static void *TableMonitorThread(void *param);
-    void RunTableMonitor(void);
-
     bool SupportsTSMonitoring(void);
 
+    HDHRChannel *GetHDHRChannel(void); 
+
   protected:
-    bool               dtvMonitorRunning;
-    pthread_t          table_monitor_thread;
 
-    FilterMap          filters; ///< PID filters for table monitoring
+    bool               streamHandlerStarted;
+    HDHRStreamHandler  *streamHandler;
+
 };
 
 #endif // HDHRSIGNALMONITOR_H
diff -r -u -N -X diff.exclude -x release.19703.0116b -x release.19703.0116c release.19703.0116b/mythtv/libs/libmythtv/hdhrstreamhandler.cpp release.19703.0116c/mythtv/libs/libmythtv/hdhrstreamhandler.cpp
--- mythtv/libs/libmythtv/hdhrstreamhandler.cpp	1969-12-31 18:00:00.000000000 -0600
+++ mythtv/libs/libmythtv/hdhrstreamhandler.cpp	2009-01-17 00:20:37.000000000 -0600
@@ -0,0 +1,829 @@
+// -*- Mode: c++ -*-
+
+#include <cassert> // remove when everything is filled in...
+
+// POSIX headers
+#include <pthread.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <sys/select.h>
+#include <sys/ioctl.h>
+
+// Qt headers
+#include <qstring.h>
+#include <qdeepcopy.h>
+
+// MythTV headers
+#include "hdhrstreamhandler.h"
+#include "hdhrchannel.h"
+#include "dtvsignalmonitor.h"
+#include "streamlisteners.h"
+#include "mpegstreamdata.h"
+#include "cardutil.h"
+
+#define LOC      QString("HDHRSH( %1 ): ").arg(_devicename)
+#define LOC_WARN QString("HDHRSH( %1 ) Warning: ").arg(_devicename)
+#define LOC_ERR  QString("HDHRSH( %1 ) Error: ").arg(_devicename)
+
+QMap<uint,bool> HDHRStreamHandler::_rec_supports_ts_monitoring;
+QMutex          HDHRStreamHandler::_rec_supports_ts_monitoring_lock;
+
+QMap<QString,HDHRStreamHandler*> HDHRStreamHandler::_handlers;
+QMap<QString,uint>               HDHRStreamHandler::_handlers_refcnt;
+QMutex                           HDHRStreamHandler::_handlers_lock;
+
+
+#define DEBUG_PID_FILTERS
+
+HDHRStreamHandler *HDHRStreamHandler::Get(uint device_id, uint tuner, QString devicename)
+{
+    QMutexLocker locker(&_handlers_lock);
+
+    QMap<QString,HDHRStreamHandler*>::iterator it =
+        _handlers.find(devicename);
+
+    if (it == _handlers.end())
+    {
+        HDHRStreamHandler *newhandler = new HDHRStreamHandler(device_id, tuner, devicename);
+        newhandler->Open();
+        _handlers[devicename] = newhandler;
+        _handlers_refcnt[devicename] = 1;
+    }
+    else
+    {
+        _handlers_refcnt[devicename]++;
+    }
+
+    return _handlers[devicename];
+}
+
+void HDHRStreamHandler::Return(HDHRStreamHandler * & ref)
+{
+    QMutexLocker locker(&_handlers_lock);
+
+    QMap<QString,uint>::iterator rit = _handlers_refcnt.find(ref->_devicename);
+    if (rit == _handlers_refcnt.end())
+        return;
+
+    if (*rit > 1)
+    {
+        *rit--;
+        return;
+    }
+
+    QMap<QString, HDHRStreamHandler*>::iterator it = _handlers.find(ref->_devicename);
+    if ((it != _handlers.end()) && (*it == ref))
+    {
+        ref->Close();
+        ref = NULL;
+        delete *it;
+        _handlers.erase(it);
+    }
+
+    _handlers_refcnt.erase(rit);
+}
+
+HDHRStreamHandler::HDHRStreamHandler(uint device_id, uint tuner, QString devicename) :
+    _control_socket(NULL),
+    _video_socket(NULL),
+    _device_id(device_id),
+    _tuner(tuner),
+    _devicename(devicename),
+    _allow_retune(false),
+
+    _start_stop_lock(true),
+    _running(false),
+
+
+    _sigmon(NULL),
+    _channel(NULL),
+
+    _pid_lock(true),
+    _listener_lock(true),
+    _hdhr_lock(true)
+{
+}
+
+HDHRStreamHandler::~HDHRStreamHandler()
+{
+    assert(_stream_data_list.empty());
+}
+
+bool HDHRStreamHandler::Open()
+{
+    if (!FindDevice())
+        return false;
+
+    return Connect();
+}
+
+void HDHRStreamHandler::Close()
+{
+    if (_control_socket)
+      hdhomerun_control_destroy(_control_socket);
+}
+
+bool HDHRStreamHandler::Connect()
+{
+    _control_socket = hdhomerun_control_create(_device_id, _device_ip);
+
+    if (!_control_socket)
+    {
+        VERBOSE(VB_IMPORTANT, LOC_ERR + "Unable to create control socket");
+        return false;
+    }
+
+    if (hdhomerun_control_get_local_addr(_control_socket) == 0)
+    {
+        VERBOSE(VB_IMPORTANT, LOC_ERR + "Unable to connect to device");
+        return false;
+    }
+
+    VERBOSE(VB_CHANNEL, LOC + "Successfully connected to device");
+    return true;
+}
+
+bool HDHRStreamHandler::FindDevice(void)
+{
+    if (!_device_id)
+        return _device_ip;
+
+    _device_ip = 0;
+
+    /* Discover. */
+    struct hdhomerun_discover_device_t result;
+    int ret = hdhomerun_discover_find_devices_custom(0, HDHOMERUN_DEVICE_TYPE_WILDCARD, _device_id, &result, 1);
+    if (ret < 0)
+    {
+        VERBOSE(VB_IMPORTANT, LOC_ERR + "Unable to send discovery request" + ENO);
+        return false;
+    }
+    if (ret == 0)
+    {
+        VERBOSE(VB_IMPORTANT, LOC_ERR + QString("device not found"));
+        return false;
+    }
+
+    /* Found. */
+    _device_ip = result.ip_addr;
+
+    VERBOSE(VB_IMPORTANT, LOC +
+            QString("device found at address %1.%2.%3.%4")
+            .arg((_device_ip>>24) & 0xFF).arg((_device_ip>>16) & 0xFF)
+            .arg((_device_ip>> 8) & 0xFF).arg((_device_ip>> 0) & 0xFF));
+
+    return true;
+}
+
+
+bool HDHRStreamHandler::EnterPowerSavingMode(void)
+{
+    return true; /* QString::null != TunerSet("channel", "none", false); */
+}
+
+QString HDHRStreamHandler::DeviceGet(const QString &name, bool report_error_return)
+{
+    QMutexLocker locker(&_hdhr_lock);
+
+    if (!_control_socket)
+    {
+        VERBOSE(VB_IMPORTANT, LOC_ERR + "Get request failed (not connected)");
+        return QString::null;
+    }
+
+    char *value = NULL;
+    char *error = NULL;
+    if (hdhomerun_control_get(_control_socket, name, &value, &error) < 0)
+    {
+        VERBOSE(VB_IMPORTANT, LOC_ERR + "Get request failed" + ENO);
+        return QString::null;
+    }
+
+    if (report_error_return && error)
+    {
+        VERBOSE(VB_IMPORTANT, LOC_ERR +
+                QString("DeviceGet(%1): %2").arg(name).arg(error));
+
+        return QString::null;
+    }
+
+    return QString(value);
+}
+
+
+QString HDHRStreamHandler::DeviceSet(const QString &name, const QString &val,
+                               bool report_error_return)
+{
+    QMutexLocker locker(&_hdhr_lock);
+
+    if (!_control_socket)
+    {
+        VERBOSE(VB_IMPORTANT, LOC_ERR + "Set request failed (not connected)");
+        return QString::null;
+    }
+
+    char *value = NULL;
+    char *error = NULL;
+    if (hdhomerun_control_set(_control_socket, name, val, &value, &error) < 0)
+    {
+        VERBOSE(VB_IMPORTANT, LOC_ERR + "Set request failed" + ENO);
+
+        return QString::null;
+    }
+
+    if (report_error_return && error)
+    {
+        VERBOSE(VB_IMPORTANT, LOC_ERR +
+                QString("DeviceSet(%1 %2): %3").arg(name).arg(val).arg(error));
+
+        return QString::null;
+    }
+
+    return QString(value);
+}
+
+QString HDHRStreamHandler::TunerGet(const QString &name, bool report_error_return)
+{
+    return DeviceGet(QString("/tuner%1/%2").arg(_tuner).arg(name),
+                     report_error_return);
+}
+
+QString HDHRStreamHandler::TunerSet(const QString &name, const QString &value,
+                              bool report_error_return)
+{
+    return DeviceSet(QString("/tuner%1/%2").arg(_tuner).arg(name), value,
+                     report_error_return);
+}
+
+bool HDHRStreamHandler::DeviceSetTarget(unsigned short localPort)
+{
+    if (localPort == 0)
+    {
+        return false;
+    }
+
+    unsigned long localIP = hdhomerun_control_get_local_addr(_control_socket);
+    if (localIP == 0)
+    {
+        return false;
+    }
+
+    QString configValue = QString("%1.%2.%3.%4:%5")
+        .arg((localIP >> 24) & 0xFF).arg((localIP >> 16) & 0xFF)
+        .arg((localIP >>  8) & 0xFF).arg((localIP >>  0) & 0xFF)
+        .arg(localPort);
+
+    if (!TunerSet("target", configValue))
+    {
+        return false;
+    }
+
+    return true;
+}
+
+bool HDHRStreamHandler::DeviceClearTarget()
+{
+    return (QString::null != TunerSet("target", "0.0.0.0:0"));
+}
+
+QString HDHRStreamHandler::GetTunerStatus() {
+    return TunerGet("status");
+}
+
+bool HDHRStreamHandler::Connected() {
+    // FIXME
+    return (_control_socket != NULL);
+}
+
+bool HDHRStreamHandler::TuneChannel(QString chn) {
+    return (QString::null != TunerSet("channel", chn));
+}
+
+bool HDHRStreamHandler::TuneProgram(QString pnum) {
+    return (QString::null != TunerSet("program", pnum, false));
+}
+
+void HDHRStreamHandler::AddListener(MPEGStreamData *data)
+{
+    VERBOSE(VB_RECORD, LOC + "AddListener("<<data<<") -- begin");
+    assert(data);
+
+    _listener_lock.lock();
+
+    VERBOSE(VB_RECORD, LOC + "AddListener("<<data<<") -- locked");
+
+    _stream_data_list.push_back(data);
+
+    _listener_lock.unlock();
+
+    Start();
+
+    VERBOSE(VB_RECORD, LOC + "AddListener("<<data<<") -- end");
+}
+
+void HDHRStreamHandler::RemoveListener(MPEGStreamData *data)
+{
+    VERBOSE(VB_RECORD, LOC + "RemoveListener("<<data<<") -- begin");
+    assert(data);
+
+    _listener_lock.lock();
+
+    VERBOSE(VB_RECORD, LOC + "RemoveListener("<<data<<") -- locked");
+
+    vector<MPEGStreamData*>::iterator it =
+        find(_stream_data_list.begin(), _stream_data_list.end(), data);
+
+    if (it != _stream_data_list.end())
+        _stream_data_list.erase(it);
+
+    if (_stream_data_list.empty())
+    {
+        _listener_lock.unlock();
+        Stop();
+    }
+    else
+    {
+        _listener_lock.unlock();
+    }
+
+    VERBOSE(VB_RECORD, LOC + "RemoveListener("<<data<<") -- end");
+}
+
+void *run_hdhr_stream_handler_thunk(void *param)
+{
+    HDHRStreamHandler *mon = (HDHRStreamHandler*) param;
+    mon->Run();
+    return NULL;
+}
+
+void HDHRStreamHandler::Start(void)
+{
+    QMutexLocker locker(&_start_stop_lock);
+
+    _eit_pids.clear(); 
+
+    if (!IsRunning())
+    {
+        pthread_create(&_reader_thread, NULL,
+                       run_hdhr_stream_handler_thunk, this);
+
+        while (!IsRunning())
+            _running_state_changed.wait(100);
+    }
+}
+
+void HDHRStreamHandler::Stop(void)
+{
+    QMutexLocker locker(&_start_stop_lock);
+
+    if (IsRunning())
+    {
+        SetRunning(false);
+        pthread_join(_reader_thread, NULL);
+    }
+}
+
+void HDHRStreamHandler::Run(void)
+{
+    SetRunning(true);
+    RunTS();
+}
+
+/** \fn HDHRStreamHandler::RunTS(void)
+ *  \brief Uses TS filtering devices to read a DVB device for tables & data
+ *
+ *  This supports all types of MPEG based stream data, but is extreemely
+ *  slow with DVB over USB 1.0 devices which for efficiency reasons buffer 
+ *  a stream until a full block transfer buffer full of the requested 
+ *  tables is available. This takes a very long time when you are just
+ *  waiting for a PAT or PMT table, and the buffer is hundreds of packets
+ *  in size.
+ */
+void HDHRStreamHandler::RunTS(void)
+{
+    int remainder = 0;
+    VERBOSE(VB_RECORD, LOC + "RunTS()");
+
+    /* Calculate buffer size */
+    uint buffersize = gContext->GetNumSetting(
+        "HDRingbufferSize", 50 * TSPacket::SIZE) * 1024;
+    buffersize /= VIDEO_DATA_PACKET_SIZE;
+    buffersize *= VIDEO_DATA_PACKET_SIZE;
+
+    // Buffer should be at least about 1MB..
+    buffersize = max(49 * TSPacket::SIZE * 128, buffersize);
+
+    VERBOSE(VB_GENERAL, QString(LOC + "HD Ringbuffer size = %1 KB").arg(buffersize / 1024));
+
+    /* Create TS socket. */
+    _video_socket = hdhomerun_video_create(0, buffersize);
+    if (!_video_socket)
+    {
+        VERBOSE(VB_IMPORTANT, LOC + "Open() failed to open socket");
+        return;
+    }
+
+    uint localPort = hdhomerun_video_get_local_port(_video_socket);
+    if (!DeviceSetTarget(localPort))
+    {
+        VERBOSE(VB_IMPORTANT, LOC_ERR + "Starting recording (set target failed). Aborting.");
+        return;
+    }
+    hdhomerun_video_flush(_video_socket);
+
+    bool _error = false;
+
+    VERBOSE(VB_RECORD, LOC + "RunTS(): begin");
+
+    int loopcount=0;
+    size_t data_count=0;
+    while (IsRunning() && !_error)
+    {
+        loopcount++;
+        if (0 == (loopcount % 1000)) {
+            QMutexLocker locker(&_listener_lock);
+            VERBOSE(VB_RECORD, LOC + QString("RunTS(): loopcount = %1, datacount = %2, listen")
+                   .arg(loopcount).arg(data_count));
+            data_count=0;
+        }
+        UpdateFiltersFromStreamData();
+
+        size_t read_size = 64 * 1024; // read about 64KB
+        read_size /= VIDEO_DATA_PACKET_SIZE;
+        read_size *= VIDEO_DATA_PACKET_SIZE;
+
+        size_t data_length;
+        unsigned char *data_buffer =
+            hdhomerun_video_recv(_video_socket, read_size, &data_length);
+
+        if (! data_buffer)
+        {
+            usleep(5000);
+            continue;
+        }
+
+        data_count+=data_length;
+        // Assume data_length is a multiple of 188 (packet size)
+        ASSERT(0 == ( data_length % 188) );
+
+        _listener_lock.lock();
+
+        if (_stream_data_list.empty())
+        {
+            _listener_lock.unlock();
+            continue;
+        }
+
+        for (uint i = 0; i < _stream_data_list.size(); i++)
+        {
+            remainder = _stream_data_list[i]->ProcessData(data_buffer, data_length);
+        }
+       
+        _listener_lock.unlock();
+        if (remainder != 0)
+            VERBOSE(VB_GENERAL, QString(LOC + "RunTS(): data_length = %1 remainder = %2")
+                    .arg(data_length).arg(remainder));
+    }
+    VERBOSE(VB_RECORD, LOC + "RunTS(): " + "shutdown");
+
+    DelAllPIDs();
+
+    DeviceClearTarget();
+    VERBOSE(VB_RECORD, LOC + "RunTS(): " + "end");
+
+    hdhomerun_video_sock_t* tmp_video_socket;
+    {
+        QMutexLocker locker(&_hdhr_lock);
+        tmp_video_socket = _video_socket;
+        _video_socket=NULL;
+    }
+     
+    hdhomerun_video_destroy(tmp_video_socket);
+
+    SetRunning(false);
+}
+
+bool HDHRStreamHandler::AddPID(uint pid, bool do_update)
+{
+    QMutexLocker locker(&_pid_lock);
+
+    vector<uint>::iterator it;
+    it = lower_bound(_pid_info.begin(), _pid_info.end(), pid);
+    if (it != _pid_info.end() && *it == pid)
+    {
+#ifdef DEBUG_PID_FILTERS
+        VERBOSE(VB_CHANNEL, "AddPID(0x"<<hex<<pid<<dec<<", " << do_update << ") NOOP");
+#endif // DEBUG_PID_FILTERS
+        return true;
+    }
+
+    _pid_info.insert(it, pid);
+
+#ifdef DEBUG_PID_FILTERS
+    VERBOSE(VB_CHANNEL, "AddPID(0x"<<hex<<pid<<dec<<")", " << do_update << ");
+#endif // DEBUG_PID_FILTERS
+
+    if (do_update)
+        return UpdateFilters();
+    return true;
+}
+
+bool HDHRStreamHandler::DelPID(uint pid, bool do_update)
+{
+    QMutexLocker locker(&_pid_lock);
+
+    vector<uint>::iterator it;
+    it = lower_bound(_pid_info.begin(), _pid_info.end(), pid);
+    if (it == _pid_info.end())
+    {
+#ifdef DEBUG_PID_FILTERS
+        VERBOSE(VB_CHANNEL, "DelPID(0x"<<hex<<pid<<dec<<", " << do_update << ") NOOP");
+#endif // DEBUG_PID_FILTERS
+
+       return true;
+    }
+
+    if (*it == pid)
+    {
+#ifdef DEBUG_PID_FILTERS
+        VERBOSE(VB_CHANNEL, "DelPID(0x"<<hex<<pid<<dec<<", " << do_update << ") -- found");
+#endif // DEBUG_PID_FILTERS
+        _pid_info.erase(it);
+    }
+    else
+    {
+#ifdef DEBUG_PID_FILTERS
+        VERBOSE(VB_CHANNEL, "DelPID(0x"<<hex<<pid<<dec<<", " << do_update << ") -- failed");
+#endif // DEBUG_PID_FILTERS
+    }
+
+    if (do_update)
+        return UpdateFilters();
+    return true;
+}
+
+bool HDHRStreamHandler::DelAllPIDs(void)
+{
+    QMutexLocker locker(&_pid_lock);
+
+#ifdef DEBUG_PID_FILTERS
+    VERBOSE(VB_CHANNEL, "DelAllPID()");
+#endif // DEBUG_PID_FILTERS
+
+    _pid_info.clear();
+
+    return UpdateFilters();
+}
+
+QString filt_str(uint pid)
+{
+    uint pid0 = (pid / (16*16*16)) % 16;
+    uint pid1 = (pid / (16*16))    % 16;
+    uint pid2 = (pid / (16))        % 16;
+    uint pid3 = pid % 16;
+    return QString("0x%1%2%3%4")
+        .arg(pid0,0,16).arg(pid1,0,16)
+        .arg(pid2,0,16).arg(pid3,0,16);
+}
+
+bool HDHRStreamHandler::UpdateFilters(void)
+{
+#ifdef DEBUG_PID_FILTERS
+    VERBOSE(VB_CHANNEL, "UpdateFilters()");
+#endif // DEBUG_PID_FILTERS
+    QMutexLocker locker(&_pid_lock);
+
+    QString filter = "";
+
+    vector<uint> range_min;
+    vector<uint> range_max;
+
+// FIXME
+//    if (_ignore_filters)
+ //       return true;
+
+    for (uint i = 0; i < _pid_info.size(); i++)
+    {
+        uint pid_min = _pid_info[i];
+        uint pid_max  = pid_min;
+        for (uint j = i + 1; j < _pid_info.size(); j++)
+        {
+            if (pid_max + 1 != _pid_info[j])
+                break;
+            pid_max++;
+            i++;
+        }
+        range_min.push_back(pid_min);
+        range_max.push_back(pid_max);
+    }
+    if (range_min.size() > 16)
+    {
+        range_min.resize(16);
+        uint pid_max = range_max.back();
+        range_max.resize(15);
+        range_max.push_back(pid_max);
+    }
+
+    for (uint i = 0; i < range_min.size(); i++)
+    {
+        filter += filt_str(range_min[i]);
+        if (range_min[i] != range_max[i])
+            filter += QString("-%1").arg(filt_str(range_max[i]));
+        filter += " ";
+    }
+
+    filter = filter.stripWhiteSpace();
+
+    QString new_filter = TunerSet("filter", filter);
+
+#ifdef DEBUG_PID_FILTERS
+    QString msg = QString("Filter: '%1'").arg(filter);
+    if (filter != new_filter)
+        msg += QString("\n\t\t\t\t'%2'").arg(new_filter);
+
+    VERBOSE(VB_CHANNEL, msg);
+#endif // DEBUG_PID_FILTERS
+
+    return filter == new_filter;
+}
+
+void HDHRStreamHandler::UpdateListeningForEIT(void)
+{
+    vector<uint> add_eit, del_eit;
+
+    QMutexLocker read_locker(&_listener_lock);
+
+    for (uint i = 0; i < _stream_data_list.size(); i++)
+    {
+        MPEGStreamData *sd = _stream_data_list[i];
+        if (sd->HasEITPIDChanges(_eit_pids) &&
+            sd->GetEITPIDChanges(_eit_pids, add_eit, del_eit))
+        {
+            for (uint i = 0; i < del_eit.size(); i++)
+            {
+                uint_vec_t::iterator it;
+                it = find(_eit_pids.begin(), _eit_pids.end(), del_eit[i]);
+                if (it != _eit_pids.end())
+                    _eit_pids.erase(it);
+                sd->RemoveListeningPID(del_eit[i]);
+            }
+
+            for (uint i = 0; i < add_eit.size(); i++)
+            {
+                _eit_pids.push_back(add_eit[i]);
+                sd->AddListeningPID(add_eit[i]);
+            }
+        }
+    }
+}
+
+bool HDHRStreamHandler::UpdateFiltersFromStreamData(void)
+{
+
+    UpdateListeningForEIT();
+
+    pid_map_t pids;
+
+    {
+        QMutexLocker read_locker(&_listener_lock);
+
+        for (uint i = 0; i < _stream_data_list.size(); i++)
+            _stream_data_list[i]->GetPIDs(pids);
+    }
+
+    uint_vec_t           add_pids;
+    vector<uint>         del_pids;
+
+    {
+        QMutexLocker read_locker(&_pid_lock);
+
+        // PIDs that need to be added..
+        pid_map_t::const_iterator lit = pids.constBegin();
+        for (; lit != pids.constEnd(); ++lit)
+        {
+            vector<uint>::iterator it;
+            it = lower_bound(_pid_info.begin(), _pid_info.end(), lit.key());
+            if (! (it != _pid_info.end() && *it == lit.key())) {
+                add_pids.push_back(lit.key());
+            }
+        }
+
+        // PIDs that need to be removed..
+        vector<uint>::iterator fit = _pid_info.begin();
+        for (; fit != _pid_info.end(); ++fit)
+        {
+            pid_map_t::const_iterator it = pids.find(*fit);
+            if(it == pids.end()) 
+                del_pids.push_back(*fit);
+        }
+    }
+
+    bool need_update = false;
+
+    // Remove PIDs
+    bool ok = true;
+    vector<uint>::iterator dit = del_pids.begin();
+    for (; dit != del_pids.end(); ++dit)
+    {
+        need_update = true;
+        ok &= DelPID(*dit, false);
+    }
+
+    // Add PIDs
+    vector<uint>::iterator ait = add_pids.begin();
+    for (; ait != add_pids.end(); ++ait)
+    {
+        need_update = true;
+        ok &= AddPID(*ait, false);
+    }
+
+    if (need_update)
+        return UpdateFilters();
+
+    return ok;
+}
+
+void HDHRStreamHandler::SetRetuneAllowed(
+    bool              allow,
+    DTVSignalMonitor *sigmon,
+    HDHRChannel       *hdhrchan)
+{
+    if (allow && sigmon && hdhrchan)
+    {
+        _allow_retune = true;
+        _sigmon       = sigmon;
+        _channel   = hdhrchan;
+    }
+    else
+    {
+        _allow_retune = false;
+        _sigmon       = NULL;
+        _channel   = NULL;
+    }
+}
+
+/** \fn HDHRStreamHandler::SupportsTSMonitoring(void)
+ *  \brief Returns true if TS monitoring is supported.
+ *
+ *   NOTE: If you are using a DEC2000-t device you need to
+ *   apply the patches provided by Peter Beutner for it, see
+ *   http://www.gossamer-threads.com/lists/mythtv/dev/166172
+ *   These patches should make it in to Linux 2.6.15 or 2.6.16.
+ */
+bool HDHRStreamHandler::SupportsTSMonitoring(void)
+{
+    return false;
+
+// FIXME
+#if 0
+    const uint pat_pid = 0x0;
+
+    {
+        QMutexLocker locker(&_rec_supports_ts_monitoring_lock);
+        QMap<uint,bool>::const_iterator it;
+        it = _rec_supports_ts_monitoring.find(_dvb_dev_num);
+        if (it != _rec_supports_ts_monitoring.end())
+            return *it;
+    }
+
+    int dvr_fd = open(_dvr_dev_path.ascii(), O_RDONLY | O_NONBLOCK);
+    if (dvr_fd < 0)
+    {
+        QMutexLocker locker(&_rec_supports_ts_monitoring_lock);
+        _rec_supports_ts_monitoring[_dvb_dev_num] = false;
+        return false;
+    }
+
+    bool supports_ts = false;
+    if (AddPIDFilter(new PIDInfoHDHR(pat_pid)))
+    {
+        supports_ts = true;
+        RemovePIDFilter(pat_pid);
+    }
+
+    close(dvr_fd);
+
+    QMutexLocker locker(&_rec_supports_ts_monitoring_lock);
+    _rec_supports_ts_monitoring[_dvb_dev_num] = supports_ts;
+
+    return supports_ts;
+#endif
+}
+
+void HDHRStreamHandler::SetRunning(bool is_running)
+{
+    _running = is_running;
+    _running_state_changed.wakeAll();
+}
+
+PIDPriority HDHRStreamHandler::GetPIDPriority(uint pid) const
+{
+    QMutexLocker reading_locker(&_listener_lock);
+
+    PIDPriority tmp = kPIDPriorityNone;
+
+    for (uint i = 0; i < _stream_data_list.size(); i++)
+        tmp = max(tmp, _stream_data_list[i]->GetPIDPriority(pid));
+
+    return tmp;
+}
diff -r -u -N -X diff.exclude -x release.19703.0116b -x release.19703.0116c release.19703.0116b/mythtv/libs/libmythtv/hdhrstreamhandler.h release.19703.0116c/mythtv/libs/libmythtv/hdhrstreamhandler.h
--- mythtv/libs/libmythtv/hdhrstreamhandler.h	1969-12-31 18:00:00.000000000 -0600
+++ mythtv/libs/libmythtv/hdhrstreamhandler.h	2009-01-17 00:09:11.000000000 -0600
@@ -0,0 +1,144 @@
+// -*- Mode: c++ -*-
+
+#ifndef _HDHRSTREAMHANDLER_H_
+#define _HDHRSTREAMHANDLER_H_
+
+#include <vector>
+using namespace std;
+
+#include <qmap.h>
+#include <qmutex.h>
+
+#include "util.h"
+#include "DeviceReadBuffer.h"
+#include "mpegstreamdata.h"
+
+class QString;
+class HDHRStreamHandler;
+class DTVSignalMonitor;
+class HDHRChannel;
+class DeviceReadBuffer;
+
+// HDHomeRun headers
+#ifdef USING_HDHOMERUN
+#include "hdhomerun_includes.h"
+#else
+struct hdhomerun_control_sock_t { int dummy; };
+#endif
+
+typedef QMap<uint,int> FilterMap;
+
+//#define RETUNE_TIMEOUT 5000
+
+class HDHRStreamHandler : public ReaderPausedCB
+{
+    friend void *run_hdhr_stream_handler_thunk(void *param);
+
+  public:
+    static HDHRStreamHandler *Get(uint device_id, uint tuner, QString devicename);
+    static void Return(HDHRStreamHandler * & ref);
+
+    void AddListener(MPEGStreamData *data);
+    void RemoveListener(MPEGStreamData *data);
+
+    void RetuneMonitor(void);
+
+    bool IsRunning(void) const { return _running; }
+    bool IsRetuneAllowed(void) const { return _allow_retune; }
+
+    void SetRetuneAllowed(bool              allow,
+                          DTVSignalMonitor *sigmon,
+                          HDHRChannel       *dvbchan);
+
+    // ReaderPausedCB
+    virtual void ReaderPaused(int fd) { (void) fd; }
+
+    QString GetTunerStatus(void);
+
+    bool Connected();
+    bool TuneChannel(QString );
+    bool TuneProgram(QString );
+
+    bool EnterPowerSavingMode();
+
+  private:
+
+    bool FindDevice();
+    bool Connect(void);
+
+    QString DeviceGet(const QString &name, bool report_error_return = true);
+    QString DeviceSet(const QString &name, const QString &value,
+                      bool report_error_return = true);
+
+    QString TunerGet(const QString &name, bool report_error_return = true);
+    QString TunerSet(const QString &name, const QString &value,
+                     bool report_error_return = true);
+
+    bool DeviceSetTarget(short unsigned int);
+    bool DeviceClearTarget();
+
+    HDHRStreamHandler(uint, uint, QString);
+    ~HDHRStreamHandler();
+
+    bool Open(void);
+    void Close();
+
+    void Start(void);
+    void Stop(void);
+
+    void Run(void);
+    void RunTS(void);
+
+    void UpdateListeningForEIT(void);
+    bool UpdateFiltersFromStreamData(void);
+
+    // Commands
+    bool AddPID(uint pid, bool do_update = true);
+    bool DelPID(uint pid, bool do_update = true);
+    bool DelAllPIDs(void);
+    bool UpdateFilters(void);
+
+    void SetRunning(bool);
+
+    PIDPriority GetPIDPriority(uint pid) const;
+    bool SupportsTSMonitoring(void);
+
+  private:
+    hdhomerun_control_sock_t  *_control_socket;
+    hdhomerun_video_sock_t    *_video_socket;
+    uint            _device_id;
+    uint            _device_ip;
+    uint            _tuner;
+    QString         _devicename;
+
+    bool              _allow_retune;
+
+    mutable QMutex     _start_stop_lock;
+    bool              _running;
+    QWaitCondition    _running_state_changed;
+    pthread_t         _reader_thread;
+    DTVSignalMonitor *_sigmon;
+    HDHRChannel       *_channel;
+
+    mutable QMutex    _pid_lock;
+    vector<uint>      _eit_pids;
+    vector<uint>      _pid_info;
+    uint              _open_pid_filters;
+    MythTimer         _cycle_timer;
+
+    mutable QMutex          _listener_lock;
+    vector<MPEGStreamData*> _stream_data_list;
+
+    mutable QMutex          _hdhr_lock;
+
+    // for caching TS monitoring supported value.
+    static QMutex          _rec_supports_ts_monitoring_lock;
+    static QMap<uint,bool> _rec_supports_ts_monitoring;
+
+    // for implementing Get & Return
+    static QMutex                       _handlers_lock;
+    static QMap<QString, HDHRStreamHandler*> _handlers;
+    static QMap<QString, uint>              _handlers_refcnt;
+};
+
+#endif // _HDHRSTREAMHANDLER_H_
diff -r -u -N -X diff.exclude -x release.19703.0116b -x release.19703.0116c release.19703.0116b/mythtv/libs/libmythtv/libmythtv.pro release.19703.0116c/mythtv/libs/libmythtv/libmythtv.pro
--- mythtv/libs/libmythtv/libmythtv.pro	2009-01-16 18:28:34.000000000 -0600
+++ mythtv/libs/libmythtv/libmythtv.pro	2009-01-17 00:09:11.000000000 -0600
@@ -451,10 +451,10 @@
     using_hdhomerun {
         # MythTV HDHomeRun glue
         HEADERS += hdhrsignalmonitor.h   hdhrchannel.h
-        HEADERS += hdhrrecorder.h
+        HEADERS += hdhrrecorder.h        hdhrstreamhandler.h
 
         SOURCES += hdhrsignalmonitor.cpp hdhrchannel.cpp
-        SOURCES += hdhrrecorder.cpp
+        SOURCES += hdhrrecorder.cpp      hdhrstreamhandler.cpp
 
         DEFINES += USING_HDHOMERUN
 
diff -r -u -N -X diff.exclude -x release.19703.0116b -x release.19703.0116c release.19703.0116b/mythtv/libs/libmythtv/tv_rec.cpp release.19703.0116c/mythtv/libs/libmythtv/tv_rec.cpp
--- mythtv/libs/libmythtv/tv_rec.cpp	2009-01-16 18:15:23.000000000 -0600
+++ mythtv/libs/libmythtv/tv_rec.cpp	2009-01-17 00:09:11.000000000 -0600
@@ -4080,17 +4080,6 @@
     }
     recorder->Reset();
 
-#ifdef USING_HDHOMERUN
-    if (GetHDHRRecorder())
-    {
-        pauseNotify = false;
-        GetHDHRRecorder()->Close();
-        pauseNotify = true;
-        GetHDHRRecorder()->Open();
-        GetHDHRRecorder()->StartData();
-    }
-#endif // USING_HDHOMERUN
-
     // Set file descriptor of channel from recorder for V4L
     channel->SetFd(recorder->GetVideoFd());
 
diff -r -u -N -X diff.exclude -x release.19703.0116b -x release.19703.0116c release.19703.0116b/mythtv/libs/libmythtv/videosource.cpp release.19703.0116c/mythtv/libs/libmythtv/videosource.cpp
--- mythtv/libs/libmythtv/videosource.cpp	2009-01-01 06:30:06.000000000 -0600
+++ mythtv/libs/libmythtv/videosource.cpp	2009-01-17 00:09:11.000000000 -0600
@@ -131,7 +131,7 @@
 class RecorderOptions : public ConfigurationWizard
 {
   public:
-    RecorderOptions(CaptureCard& parent);
+    RecorderOptions(CaptureCard& parent, QString type);
     uint GetInstanceCount(void) const { return (uint) count->intValue(); }
 
   private:
@@ -1355,6 +1355,16 @@
         addChild(new SignalTimeout(parent, 1000, 250));
         addChild(new ChannelTimeout(parent, 3000, 1750));
         addChild(new SingleCardInput(parent));
+	//addChild(new InstanceCount(parent));
+
+        TransButtonSetting *buttonRecOpt = new TransButtonSetting();
+        buttonRecOpt->setLabel(tr("Recording Options"));    
+        addChild(buttonRecOpt);
+
+        connect(buttonRecOpt, SIGNAL(pressed()),
+            &parent,      SLOT(  recorderOptionsPanelHDHomerun()));
+
+
     };
 
   private:
@@ -1504,7 +1514,7 @@
 {
     MSqlQuery query(MSqlQuery::InitCon());
     QString qstr =
-        "SELECT cardid, videodevice, cardtype "
+        "SELECT cardid, videodevice, cardtype, dbox2_port "
         "FROM capturecard "
         "WHERE hostname = :HOSTNAME "
         "ORDER BY cardid";
@@ -1524,10 +1534,18 @@
         uint    cardid      = query.value(0).toUInt();
         QString videodevice = query.value(1).toString();
         QString cardtype    = query.value(2).toString();
+	QString hdhrTuner   = query.value(3).toString(); 
 
         if ((cardtype.lower() == "dvb") && (1 != ++device_refs[videodevice]))
             continue;
 
+        if (cardtype.lower() == "hdhomerun")
+        {
+            QString altvideodevice = videodevice + ":" + hdhrTuner;
+ 	    if (1 != ++device_refs[altvideodevice])
+               continue;
+        }
+
         QString label = CardUtil::GetDeviceLabel(
             cardid, cardtype, videodevice);
 
@@ -1548,8 +1566,17 @@
         if (CardUtil::IsTunerSharingCapable(type))
         {
             QString dev = CardUtil::GetVideoDevice(cardid);
-            vector<uint> cardids = CardUtil::GetCardIDs(dev, type);
-            new_cnt = cardids.size();
+            if (type == "HDHOMERUN")
+            {
+                uint hdhrTuner = CardUtil::GetHDHRTuner(cardid);
+                vector<uint> cardids = CardUtil::GetCardIDs(dev, hdhrTuner);
+                new_cnt = cardids.size();
+            }
+            else
+            {
+                vector<uint> cardids = CardUtil::GetCardIDs(dev, type);
+                new_cnt = cardids.size();
+            }
         }
     }
     instance_count = new_cnt;
@@ -1576,9 +1603,20 @@
 
     if (!init_cardid)
     {
+        uint cid_size = 0;
         QString dev = CardUtil::GetVideoDevice(cardid);
-        vector<uint> cardids = CardUtil::GetCardIDs(dev, type);
-        if (cardids.size() > 1)
+        if (type == "HDHOMERUN")
+        {
+            uint hdhrTuner = CardUtil::GetHDHRTuner(cardid);
+            vector<uint> cardids = CardUtil::GetCardIDs(dev, hdhrTuner);
+            cid_size = cardids.size();
+        }
+        else
+        {
+            vector<uint> cardids = CardUtil::GetCardIDs(dev, type);
+            cid_size = cardids.size();
+        }
+        if (cid_size > 1)
         {
             VERBOSE(VB_IMPORTANT,
                     "A card using this video device already exists!");
@@ -1587,7 +1625,16 @@
         return;
     }
 
-    vector<uint> cardids = CardUtil::GetCardIDs(init_dev, type);
+    vector<uint> cardids;
+    if (type == "HDHOMERUN")
+    {
+        uint hdhrTuner = CardUtil::GetHDHRTuner(cardid);
+        cardids = CardUtil::GetCardIDs(init_dev, hdhrTuner);
+    }
+    else
+    {
+        cardids = CardUtil::GetCardIDs(init_dev, type);
+    }
 
     if (!instance_count)
         instance_count = max((size_t)0, cardids.size()) + 1;
@@ -2644,7 +2691,7 @@
 
     MSqlQuery query(MSqlQuery::InitCon());
     query.prepare(
-        "SELECT cardid, videodevice, cardtype "
+        "SELECT cardid, videodevice, cardtype, dbox2_port "
         "FROM capturecard "
         "WHERE hostname = :HOSTNAME "
         "ORDER BY cardid");
@@ -2663,10 +2710,19 @@
         uint    cardid      = query.value(0).toUInt();
         QString videodevice = query.value(1).toString();
         QString cardtype    = query.value(2).toString();
+        QString hdhrTuner   = query.value(3).toString();
 
         if ((cardtype.lower() == "dvb") && (1 != ++device_refs[videodevice]))
             continue;
 
+        if (cardtype.lower() == "hdhomerun")
+        {
+            QString altvideodevice = videodevice + ":" + hdhrTuner;
+            if (1 != ++device_refs[altvideodevice])
+               continue;
+        }
+
+
         QStringList        inputLabels;
         vector<CardInput*> cardInputs;
 
@@ -2908,7 +2964,7 @@
     connect(buttonDiSEqC, SIGNAL(pressed()),
             this,         SLOT(  DiSEqCPanel()));
     connect(buttonRecOpt, SIGNAL(pressed()),
-            &parent,      SLOT(  recorderOptionsPanel()));
+            &parent,      SLOT(  recorderOptionsPanelDVB()));
 }
 
 DVBConfigurationGroup::~DVBConfigurationGroup()
@@ -2953,16 +3009,25 @@
     }
 }
 
-void CaptureCard::recorderOptionsPanel()
+void CaptureCard::recorderOptionsPanelHDHomerun()
+{
+    reload();
+
+    RecorderOptions acw(*this, "HDHOMERUN");
+    acw.exec();
+    instance_count = acw.GetInstanceCount();
+}
+
+void CaptureCard::recorderOptionsPanelDVB()
 {
     reload();
 
-    RecorderOptions acw(*this);
+    RecorderOptions acw(*this, "DVB");
     acw.exec();
     instance_count = acw.GetInstanceCount();
 }
 
-RecorderOptions::RecorderOptions(CaptureCard &parent)
+RecorderOptions::RecorderOptions(CaptureCard &parent, QString type)
     : count(new InstanceCount(parent))
 {
     VerticalConfigurationGroup* rec = new VerticalConfigurationGroup(false);
@@ -2970,10 +3035,14 @@
     rec->setUseLabel(false);
 
     rec->addChild(count);
-    rec->addChild(new DVBNoSeqStart(parent));
-    rec->addChild(new DVBOnDemand(parent));
-    rec->addChild(new DVBEITScan(parent));
-    rec->addChild(new DVBTuningDelay(parent));
+    if (type == "DVB")
+    {
+        rec->addChild(new DVBNoSeqStart(parent));
+        rec->addChild(new DVBOnDemand(parent));
+        rec->addChild(new DVBEITScan(parent));
+        rec->addChild(new DVBTuningDelay(parent));
+    }
 
     addChild(rec);
 }
+
diff -r -u -N -X diff.exclude -x release.19703.0116b -x release.19703.0116c release.19703.0116b/mythtv/libs/libmythtv/videosource.h release.19703.0116c/mythtv/libs/libmythtv/videosource.h
--- mythtv/libs/libmythtv/videosource.h	2008-03-15 23:22:10.000000000 -0500
+++ mythtv/libs/libmythtv/videosource.h	2009-01-17 00:09:11.000000000 -0600
@@ -477,7 +477,8 @@
     uint GetInstanceCount(void) const { return instance_count; }
 
 public slots:
-    void recorderOptionsPanel();
+    void recorderOptionsPanelDVB();
+    void recorderOptionsPanelHDHomerun();
 
 private:
 
