IPTV Encoders as a Capture Device

From MythTV Official Wiki
Jump to: navigation, search

This document describes the process of setting up a single channel IPTV Encoder as a capture source for MythTV. The example is built for a LINUX environment, but this should be a viable solution on other OS platforms as well.

Description

With an aging HD-PVR, more new video devices coming to market without component outputs and HDCP impacting MythTV users ability to record directly from the HDMI digital signals, I set about the process of finding an alternate way to keeping my MythTV installation working. After a great deal of searching, I found a solution that worked for me – a single channel IPTV HDMI encoder. These devices are available from a number of sources and convert HDMI output to an MPEGTS stream transmitted over 1000Base-T Ethernet. I will describe how I set these up as an input device for MythTV. I have been running this setup for a couple of months and everything is working well.


The IPTV encoder does a lot of things well.

  • It's reasonably simple to configure.
  • It encodes the HDMI signals to a very good quality H.264 video stream
  • It transmits the IP/TV signal in a variety of protocols which I can record/process with the MythTV recorder
  • The latency is reasonable.
  • The tested encoder and researched products all support HDCP V1.x protocols.
  • The encoder supports multiple simultaneous output streams, and
  • Unlike the older HD-PVR capture devices, the IP/TV encoders tested seamlessly switch between display resolutions

There are however some limitation:

  • 480i video is not supported cleanly. This can be trivially worked around by setting the STB output to a fixed value of 480P or greater
  • The encoder can not pass 5.1 or 7.1 audio, only 2 channel Stereo is supported.
  • The output of the early devices is limited to 30 Frames Per second (fps) by the Web GUI, but newer devices support 60 frames per second
  • Only IPv4 networks are supported in the current firmware

Addressing the limitations

So this is not the perfect solution, but it works quite well in practice.

The limitation of 30 fps seems like it might be a problem, so here's my take on that limit.

The 30 fps limit would obviously not be an issue for any p30, p25 or p24 broadcasts, streams or disc video sources. In fact, the capture from these sources looks excellent with reasonable bit rates configured. If, however, your input is a 720p60 ( or 720p50) source there is a quality of capture issue that would concern many users.

Deinterlacing broadcast ( or cable or satellite ) TV from interlaced formats, such as 1080i, is always a bit of a concern in that there is not a perfect way to handle complete image fidelity in moving 60 ½ frames per second to a fixed progressive frame rate. Based on experience and after using this setup for a few months, the deinterlaced versions of 60i streams from these encoders is of reasonable quality and is not terribly noticeable. So I stopped worrying about this limitation.


The following does not apply to the newer devices as the GUI now support a full 60 frames per second at all resolutions

Dealing with 720p60 content.... After some detective work, and reading the specs on the main encoder chip used in the devices listed, I discovered that these devices will support 720p60, and even 1080p60 if we shut down all other streams, however the GUI limits you to 30 FPS . Based on some experiments, I found an undocumented web API that will let me change the frame rate on the encoder interfaces to 60fps. These changes to the encoder configuration can be automated in a script or manually executed manually in your browser.

I do not have a video source to test 1080p at 60fps, but the 720p60 sources I have tested worked very well and delivered great video quality.

The Net Result

Leveraging multiple encoding stream configurations, A user can set the main encoder to a high resolution stream, e.g. 1920x1080 or “auto”at 30 fps, and the secondary stream to a different resolution, e.g. 1280x720 at 60fps, using the above API calls. With an appropriate m3u file you can deal with what ever stream your provider delivers with excellent video quality.

Audio is still limited to Stereo only at this time.

Requirements

Here's what you need to implement this arrangement

  • A running MythTV installation (0.28+),
  • One or more IP/TV encoders ( a list of known suppliers is provided below ),
  • Ethernet Switch (as needed),
  • 1x2 HDMI splitter ( as needed )
  • Ethernet and HDMI Cables as required,
  • Skills to install and configure BASH scripts on Linux,
  • Either the wget or curl programs must be installed on your system, and
  • Python 3 must be installed to support the mythtv_encoder_status helper script provided.
  • and of course, a STB with an HDMI output.


Base Facts

  • The IPTV Encoder has the ability to compress and stream HDMI signals over the HTTP protocol as an MPEGTS stream.
  • MythTV offers an IP/TV Network Recorder called IPTV Recorder ( also known as FREEBOX).
  • MythTV 0.28 support capture of HTTP stream videos
  • Through the use of several system event scripts we can implement the needed channel change and controls
  • With the tools above it is possible to capture an HDMI stream ( with a few limitations ) and record that content in MythTV.


IP/TV HDMI Encoders

There are numerous vendors selling these single channel IP/TV encoders with HDMI input. Here are a few of the devices I have found.

  • Colable Electronics Co - COL-7101H
  • Dtvane - DMB-8800A and DMB-8900A
  • Minetech - MV-E1002 asn MC-E1005 series
  • Oupree - OPR-NH-100 series
  • Sumhen - MV-1004
  • TBS - TBS2216
  • TBS - TBS2603
  • Telecast - NLE-01H
  • Unisheen - BM-1000-HDMI, BM-2650-HDMI, BM-3000-HDMI, and BM-3500 series


All share the same specifications and appear to be manufactured by the same company in China.

Typical Specifications

Video 
Input 1x HDMI( 1.3a or 1.4) HDCP
Supports HDMI Resolution 1920x1080P/1080i/720P /480P@50/60Hz

480i is not supported.

I have not been able to test 576p video, but the configuration panel implies that this will work...

Encoding H.264/AVC High Profile Level 4.0 or, for the more expensive units H.265 HVEC
Data Rate 0.8Mbps~12Mbps
Rate Control CBR/VBR
GOP Structure IBBP
Advanced Pretreatment De-interlacing, Noise Reduction, Sharpening
Audio 
Encoding AAC
Sampling rate Auto
Bit-rate 32K/48K/64K/96K/128K/160K/192K
Sampling precision 24 bit
Data Rate 64Kb/s~384Kb/s
System 
Ethernet 1000 Base-T Ethernet interface

IPv4 ONLY

Protocol MPEGTS over HTTP unicast/multicast;RTSP;RTMP.
Control Interface WEB
Others 
Dimension (W× L× H) 170*130*30mm
Weight 0.5kg
Temperature 0-45(work),-20-80(storage)
Power 12V/DC
Consumption 6W


Installation/Configuration

Create a directory on your MythBackend to store the executable script files provided. On my Ubuntu based system I use the “/usr/local/bin” directory. The /home/mythtv/bin directory would also work. The important part is that the target directory must be that in in the execution path for the mythtv user.


Hardware Setup

Cable up your IP/TV encoder. The attached diagram roughly describes the setup I have installed. Other options are possible,

Sample Cable Diagram

                       +---HDMI Cable--- IPTV Encoder ---Ethernet_Switch--- MythTV Backend
                       |
                       |
STB -- HDMI Cable-- 1x2 HDMI Splitter  
                       |
                       |
                       +---HDMI Cable--- TV


Configure the IPTV boxes

Follow the directions that came with the IP/TV encoder regarding the device setup. All of the user guides I have seen provide very minimal setup information, but they are enough to get things running


Make certain that the IP/TV encoder has a static IPv4 address in your network. Adjusting to dynamically assigned IP addresses, while very possible, will not be covered in this document. The IP/TV encoder boxes listed above have slightly different web page designed, all have a Network tab to set up the IP address, netmask, and gateway information. None of the boxes I have researched offer IPV6 support at this time


Also, make note of the password you assign during the configuration. It will be required to set up the scripts shown below.


When you configuring the “Main Stream” tab on the encoder, they following setting have been shown to work to good effect:

 H.264 Level:          High Profile
 Encoding Frame Rate:  30  (60 is the device GUI supports that rate )
 Bitrate Control:      vbr
 Key interval:         30
 Encoding size:        auto
 MinQP:                3
 MaxQP:                32
 MaxBitrate:           10000
 Audio bitrate:        192000
 Audio Channel:        L+R
 Audio Codec:          AAC
 Resample:             Disable
 HTTP:                 /hdmi, Enable
 HTTP Port:            80
 RTSP:                 Disable
 Multicast IP          Disable
 RTMP server ip:       Disable


The default picture quality settings don't provide the best quality. A suggested set of “Image Quality Settings” is provided below.

 Brightness:  37 
 Contrast:    60
 Hue          50 
 Saturation   30


When you configuring the “Secondary Stream” tab on the encoder, the following setting have proven to work well.

 H.264 Level:          High Profile
 Encoding Frame Rate:  60     # note the trick listed above
 Bitrate Control:      vbr
 Key interval:         30
 Encoding size:        1280x720
 MinQP:                3
 MaxQP:                32
 MaxBitrate:           10000
 HTTP:                 /hdmi_ext, Enable
 HTTP Port:            80


Once all required changes have been made, apply the updates and reboot the IP/TV encoder from the web screen interface.


To set the older encoders to 60 fps, you will need to leverage an undocumented API. Here's an example


For 60 fps the Main stream:
http://YourEncoderIP/set_codec?type=hdmi&input_fps=60 Followed by an encoder reboot
or .....
For the 60 fps Secondary stream:
http://YourEncoderIP/set_codec?type=hdmi_ext&input_fps=60 Followed by an encoder reboot
To reboot the encoder you can use the following web API -- http://YourEncoderIP/reboot -- or use the normal web menus


This 60fps work around should only be applied to one channel at a time, and needs to be done after your done editing the basic configuration in the web GUI.


Testing can be accomplished with the VLC media player. The “Network URL” will be something like: http://YourEncodeIP:80/hdmi

Configure MythTV

Creating the .m3u files

Each IP/TV Network Recorder (FREEBOX), requires a .m3u playlist as a channel list. The channel scanner on MythTV fetches the config file. Create a file with your channel listings. Store this any place you like., as a suggestion store the file in the mythtv users home directory.

Here is a sample of the /home/mythtv/Encoder.m3u format.

#EXTM3U
#EXTINF:0,71 - GSN
#EXTMYTHTV:xmltvid=14909
http://192.168.X.X:80/hdmi
#EXTINF:0,202 - CNN
#EXTMYTHTV:xmltvid=10142
http://192.168.X.X:80/hdmi
#EXTINF:0,204 - HLN
#EXTMYTHTV:xmltvid=10145
http://192.168.X.X:80/hdmi
#EXTINF:0,206 - ESPN
#EXTMYTHTV:xmltvid=10179
http:/192.168.X.X:80/hdmi_ext
#EXTINF:0,207 - ESPNEWS
#EXTMYTHTV:xmltvid=16485
http://192.168.X.X:80/hdmi_ext

This will in all likelihood be a big configuration file. Read ahead, you will see a spreadsheet to assist in generating the needed m3u file.

Add the IP/TV Network Recorder

Startup your MythTV Setup program ( mythtv-setup ).

For each encoder you have to add a Network Recorder:

"2. Capture cards" -> "New capture card".

Key parameters include:

Card Type: IPTV Recorder
M3U URL: file:///home/mythtv/Encoder.m3u or your locally created m3u file
Make certain that the max wait time in MythTV for tuning this device is set to no less that 40000 ms (40 sec), the encoder reboot is slow.

If you like, you may create a new video source for the encoder or leverage an existing video source

Then make the Input Connections:

"5. Input connections" -> "Select the new "Freebox” device

Select the video source and "Scan for channels"

The channel change scripts

The IP/TV ( Freebox ) recorder in MythTV does not support the direct addition of an external channel changer script. To accomplish the same purpose, we can take advantage of the System Event handlers.

For our purposes, we will leverage five systems events:

  • Master backend started
  • Master backend shutdown
  • Recording pending
  • Recording started
  • Recording finished

After you setup the MythTV capture card, you will need the CardID for your new device encoder. The simplest way I have found to get this information is through the MythTV Services APIs. Specifically, entering the following into a browser window on your new back end server, adjusting the IP address as appropriate.

http://BackendServerIP:6544/Capture/GetCaptureCardList?CardType=FREEBOX

This will list out all the IPTV (Freebox) “cards” on your system. The Card ID will be in the <CardId>X</CardId> field. If you have more than one IPTV recorder defined, this will show all the recorders and this will help narrow the list of options. Once the correct CardID is available, the case statements in the following scripts must be updated appropriately.

The bash scripts provided are written to support a DirecTV STB, that's my environment. You will need to be modify the scripts in 3 ways:

  1. Update the case statements as described above,
  2. Update the scripts to address the proper power on/off and channel change requirements of your STB, and
  3. Update the configuration variables reflect the IP/TV encoder IP address and password in your environment.

I've isolated these changes in the scripts to keep things simple.

NOTE: For these scripts to work either “curl” or “wget” must be installed on your back end system as well as the provide scripts.

NOTE: At least for firmware v1.0.85 on the TBS2603 encoder, the URL to reboot the box is not http://EncoderIP:80/reboot. Instead, you must use http://EncoderIP:80/cgi-bin/reboot.cgi?t=12 in the scripts below.

Once the scripts have been created on your system, they need to be added to your system events script definitions. In mythtv-setup these can be added in the “System Events” section. The scripts can also be added in mythfrontend or the webfrontend applications. When adding these scripts to the Events make certain to add the input parameters as shown in the usage comment.

Once the scripts loaded and updated to reflect the installed STB, the configuration is complete.

LiveTV now works properly with one limitation. The time needed to reset the encoder is quite long ( over 30 seconds ). This means that the start-up of a live TV viewing takes a long time. after that changing channels is reasonably fast.

Here are the developed script files.

mythtv_master_backend_start_stop.sh

This script should be loaded to both the "Master backend started" and "Master backend shutdown" events. The script takes no arguments and simply cleans up any left over lock files.

#!/bin/bash -x

# Copyright (c) 2015 Richard Brandolino <rrbrandolino at gmail.com >

# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:  

# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.


# usage mythtv_master_backend_start_stop.sh

logfile="/var/log/mythtv/MyScripts.log" # point this to where you want the log files

echo `date` "master_backend_start_stop.sh: launch" >> $logfile

lockfile="/tmp/iptvencoder.noboot" # we set this file as a lock to minimize reboots in Live TV mode
Pending_lockfile="/tmp/iptvencoder.pending" # we set this file as a block to STB shutdown when a recording is pending

# clear any left over lock files

rm -f "$lockfile"
rm -f "$Pending_lockfile"

exit 0

mythtv_recording_pending.sh

#!/bin/bash -x

# Copyright (c) 2015 Richard Brandolino <rrbrandolino at gmail.com >

# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE. 


# usage:  mythtv_recording_pending.sh %CARDID% %SECS% %CHANID%
#
# we utilize either curl or wget to reset the encoder box as needed.... 
# you need one of the 2 programs installed

logfile="/var/log/mythtv/MyScripts.log" # point this to where you want the log files 

echo `date` "pending.sh: launch" $* >> $logfile

CardID="$1" 
Time="$2"
Channel="$3" 

######### you need to update the following 4 variables to fit your installation ##############
Chan_Change_Cmd="/usr/local/bin/directtv_http.pl" 
DTV_Device="192.168.x.x"  

Encoder_IP="192.168.x.y"  
Encoder_Passwd="admin"  
##############################################################################################

lockfile="/tmp/iptvencoder.noboot" # we set this file as a lock to minimize reboots in Live TV mode
Pending_lockfile="/tmp/iptvencoder.pending" # we set this file as a block to STB shutdown when a recording is pending

echo `date` "pending.sh: CardID" $CardID >> $logfile

Curl=`which curl`
Wget=`which wget`

if [ -z "$Curl" ]
then
    if [ -z "$Wget" ]
    then
      echo "pending.sh: neither curl nor wget is installed in PATH" >> "$logfile"
      exit 1
    fi
fi

#############################################################################
#####  This function turns on the STB and clears any on screen messages #####
#####        this will need to be modified to address your environment  #####
#############################################################################

PowerOnAndClear () { 
        
        #  turn on the device
        ( $1 ip $2 on )
        echo `date` "Cardid" $3 "pending.sh:  on" $? >> $logfile 

        #clear if the "sleep mode" was entered
        ( $1 ip $2 key enter )

        echo `date` "Cardid" $3 "pending.sh:  enter" $? >> $logfile

        # clear any channel headers
        ( $1 ip $2 key exit )
        echo `date` "Cardid" $3 "pending.sh:  exit" $? >> $logfile

}  
###############################################################################

# Power on and clear box at the 60 event
# if cardid is 1 change channel 2 sec before the recording in to start

case $CardID in

1)
        if [ "$Time" -ge 35 ] && [ "$Time" -lt 80 ]
        then
          
          touch "$Pending_lockfile" # create a lock file to flag the recoerding pending state

          Encoder_status=`mythtv_encoder_status --encoder=$CardID`
          if [ "$Encoder_status" = "Idle" -a ! -f $lockfile ]
          then
       
               if [ -z "$Curl" ]
               then
                    curl -v http://$Encoder_IP:80/reboot -u admin:$Encoder_Passwd
               else
                    wget -v --http-user=admin --http-password="$Encoder_Passwd" http://$Encoder_IP:80/reboot
               fi
               
               echo `date` "pending.sh: Cardid $CardID reset encoder" $? >> $logfile
               
          else
          
               echo `date` "pending.sh: Cardid $CardID do not reset encoder" $? >> $logfile
               
          fi

          PowerOnAndClear $Chan_Change_Cmd $DTV_Device $CardID
        
        elif [ "$Time" -le 32 ] # change channel on the 30 sec prestart event and restart encoder
        then

           Channel=${Channel#?}
           Channel=$((10#$Channel))

           Sleeptime="$((Time - 2))" # change the channel at the last second

           sleep $Sleeptime

           ###### update the channel change command as needed #######
           ( $Chan_Change_Cmd ip $DTV_Device $Channel &)  
           ###########################################################

           echo `date` "pending.sh: Cardid $CardID change channel" $? >> $logfile

           sleep 5 # wait a few seconds until the encode state has changed to "Recording"
           rm -r "$Pending_lockfile" # we are no longer in a pending state

        fi
        ;;

*)
        echo `date` "pending.sh: Cardid" $CardID "NO ACTION" $? >> $logfile
        ;;
esac
exit 0

mythtv_recording_started.sh

#!/bin/bash -x

# Copyright (c) 2015 Richard Brandolino <rrbrandolino at gmail.com >

# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

# usage mythtv_recording_started.sh %CARDID% %CHANID% %STARTTIME%

# make sure the max wait time in MythTV for tuning this device is set
# no less that 40000 ms (40 sec), the encoder reboot is slow

logfile="/var/log/mythtv/MyScripts.log"  # point this to where you want the log files

CardID="$1"
Channel="$2"
StartTime="$3"

echo $StartTime "mythtv_recording_started.sh launch" >> "$logfile" 

######### you need to update the following 4 variables to fit your installation ##############
Chan_Change_Cmd="/usr/local/bin/directtv_http.pl" 
DTV_Device="192.168.x.x"  

Encoder_IP="192.168.x.y"  
Encoder_Passwd="admin"  
##############################################################################################


echo $StartTime "recording_started.sh: CardID" $CardID "Channel " $Channel >> "$logfile"

lockfile="/tmp/iptvencoder.noboot" # we set this file as a lock to minimize reboots in Live TV mode

Curl=`which curl`
Wget=`which wget`

if [ -z "$Curl" ]
then
    if [ -z "$Wget" ]
    then
      echo $StartTime "recording_started.sh: neither curl nor wget is installed in PATH" >> "$logfile"
      exit 1
    fi
fi

Enc_Status=`which mythtv_encoder_status`

if [ -z "$Enc_Status" ]
then
   echo $StartTime "recording_started.sh: mythtv_encoder_status is not installed in PATH" >> "$logfile"
   exit 1
fi

#############################################################################
#####  This function turns on the STB and clears any on screen messages #####
#####        this will need to be modified to address your environment  #####
#############################################################################

PowerOnAndClear () { 
        
        #  turn on the device
        ( $1 ip $2 on )
        echo $StartTime "Cardid" $3 "recording_started.sh:  on" $? >> $logfile 

        #clear if the "sleep mode" was entered
        ( $1 ip $2 key enter )

        echo $StartTime "Cardid" $3 "recording_started.sh:  enter" $? >> $logfile

        # clear any channel headers
        ( $1 ip $2 key exit )
        echo $StartTime "Cardid" $3 "recording_started.sh:  exit" $? >> $logfile

}  

#############################################################################

# Power on and clear box at the 60 event
# if cardid is 1 and this is LiveTV, reset the encoder, power on the device as
# needed and/or change the channel

case $CardID in

1)
       
     Encoder_status=`mythtv_encoder_status --encoder=$CardID`
     if [ "$Encoder_status" = "WatchingLiveTV" ]
     then

          # reboot and power on using the right commands IF the lock is not set

          if [ ! -f $lockfile ]
          then
               if [ "$Curl" != "" ]
               then
                    curl -v http://$Encoder_IP:80/reboot -u admin:$Encoder_Passwd
                    echo $StartTime "recording_started.sh: Cardid $CardID Curl reset encoder" $? >> $logfile
               elif [ "$Wget" != "" ]
               then
                    wget -v --http-user=admin --http-password="$Encoder_Passwd" http://$Encoder_IP:80/reboot
                    echo $StartTime "recording_started.sh: Cardid $CardID wget reset encoder" $? >> $logfile
               fi
               
               touch "$lockfile" # create a lock file so we don't reboot again until needed
               PowerOnAndClear $Chan_Change_Cmd $DTV_Device $CardID

          fi

          Channel=${Channel#?}
          Channel=$((10#$Channel))

          ###### update the channel change command as needed #######
          ($Chan_Change_Cmd ip $DTV_Device $Channel &)  #update for your STB
          ###########################################################

          echo $StartTime "recording_started.sh: Cardid $CardID change channel" >> $logfile

     fi

     ;;

*)
     echo $StartTime "recording_started.sh: Cardid" $CardID "NO ACTION" >> "$logfile"

     ;;
esac
exit 0


mythtv_recording_finished.sh

#!/bin/bash -x
  
# Copyright (c) 2015 Richard Brandolino <rrbrandolino at gmail.com >

# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.


# usage: mythtv_recording_finished.sh %CARDID% %CHANID% %STARTTIME% 

logfile="/var/log/mythtv/MyScripts.log"  # point this to where you want the log files

CardID="$1" 
Channel="$2"
StartTime="$3"

echo $StartTime "finished.sh: launch" $* >> $logfile 
echo $StartTime "recording_finished.sh: CardID" $CardID "Channel " $Channel >> "$logfile"

######### you need to update the following 2 variables to fit your installation ##############
DTV_Device="192.168.x.y"
Chan_Change_Cmd="/usr/local/bin/directtv_http.pl"
##############################################################################################

lockfile="/tmp/iptvencoder.noboot" # we set this file as a lock to minimize reboots in Live TV mode
Pending_lockfile="/tmp/iptvencoder.pending" # we set this file as a block to STB shutdown when a recording is pending
Sleep_Time=300 # delay for checking if we should power down the STB in seconds

case $CardID in

1)

     Encoder_status=`mythtv_encoder_status --encoder=$CardID`

     # Clear the lock if we find we're not in WatchingLiveTV mode. This is a bit of a kludge, but it's the best solution I have. 
     # The big problem will be if we go from WatchingLiveTV to something else and back to WatchingLiveTV 
     # in a short time window we'll end up resetting the encoder more than needed. We really need a LiveTV ended event action

     if [ "$Encoder_status" != "WatchingLiveTV" ]
     then
         rm -f "$lockfile" "$Pending_lockfile"
     fi

     if [ "$Encoder_status" = "Idle" ]
     then
         sleep $Sleep_Time # wait a few minutes to see if we should turn off the STB
         Encoder_status=`mythtv_encoder_status --encoder=$CardID`
         if [ "$Encoder_status" = "Idle" -a ! -f $Pending_lockfile ] # if we're still idle and a recoding is not pending shut off the STB
         then

             ####### update the STB Device OFF  command as needed #######    
             ( $Chan_Change_Cmd ip $DTV_Device off )  #update this for your STB
             ############################################################

             echo $StartTime "finished.sh: Cardid $CardID, time $Sleep_Time - Turn Off Device" >> $logfile

         else # if we're not still idle do nothing
            echo $StartTime "finished.sh: Cardid $CardID, time $Sleep_Time - Do Not Turn Off Device" >>  $logfile
         fi
     fi

     ;; 
*)
      
     echo $StartTime "finished.sh: Cardid $CardID NO ACTION" >> $logfile
     ;;

esac
exit 0


I have also created a small support script that tells me if the Myth encoder is busy. I use this to decide when to do a device rest or if I can turn off the STB

mythtv_encoder_status:

#!/usr/bin/env python

# Copyright (c) 2015 Richard Brandolino <rrbrandolino at gmail.com > 

# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

#
# Parse a Services API response to check the encoder status
#

import urllib2
from xml.etree import cElementTree as ET
from optparse import OptionParser

#trigger variable to check if no CardID was found 
found=0 


# Parse the command Line 

parser = OptionParser()

parser.add_option("-b", "--backend", dest="backend_addr",
                  help="Specify the hostname or IP address of the backend. Default  = localhost",
                  metavar="Backend_Master", default="localhost")
parser.add_option("-e", "--encoder", dest="encoder_number", type="int",
                  help="Specify the Encoder Card ID", metavar="CardID")

(options, args) = parser.parse_args()

GET_URL='http://'+options.backend_addr+':6544/Dvr/GetEncoderList'


try:
    get_response = ET.parse(urllib2.urlopen(GET_URL))
except:
    raise SystemExit('GetEncoderList failed. Is the backend running at the hostname/address provided?')

for element in get_response.findall('Encoders/Encoder'): 
    id = element.findtext('Id')
    state = element.findtext('State')
    if int(id) == options.encoder_number :
       found = 1
       if ( state == '0' ):
          print 'Idle'
       elif ( state == '1' ):
          print 'WatchingLiveTV' 
       elif ( state == '6' ):
          print 'WatchingRecording' 
       elif ( state == '7' ):
          print 'Recording' 
       elif ( state == '8' ):
          print 'ChangingState' 
       elif ( state == '-1' ):
          print 'Error' 

if ( found == 0 ): 
    raise SystemExit('Encoder Unknown to the specified MythTV backend. Please validate the encoder/CardID number')

m3u file generation

The provided m3u creator spreadsheet was built to allow copying data from the SchedulesDirect "reports" screen directly into the first columns of the spreadsheet. Columns F, G and H must be updated to reflect the encoders IP address, the HTTP port assigned on the encoders set-up page (“Main Stream” > “HTTP Port:” or “second stream” > “HTTP Port:”), and the HTTP path ((“Main Stream” > “HTTP:” or “second stream” > “HTTP:”).


This same form can be manually updated by people utilizing other data sources for their channel lists and schedules.

Sample


M3u spreadsheet screenshot.png

Here's the Google Doc version of the Spreadsheet [1]

After adding all the correct data, you can copy the last column (Column I ) to a text file using your favorite editor. Make certain that the the first line of the file is “#EXTM3U”

Alternative m3u file generation

The following script will generate the .m3u file from the SchedulesDirect database entries. The .m3u file goes to stdout, and can be redirected to a file.

#! /bin/sh

encoderIP=xx.xx.xx.xx
encoderPort=8080
sourceID=2

echo "#EXTM3U"
mysql mythconverg -r -s -e "select channum,xmltvid,callsign from channel where sourceid=${sourceID};" |\
   while read channum xmltvid callsign
   do
       echo "#EXTINF:0,$channum - $callsign"
       echo "#EXTMYTHTV:xmltvid=$xmltvid"
       echo "http://${encoderIP}:${encoderPort}/hdmi"
   done

Getting closed captions

If you have the necessary supplemental hardware, the procedure described at Captions_with_HD-PVR can also be used with any of these IPTV encoders. This allows you to obtain a .srt file of the closed captions for the program being recorded, which will be available for live TV or recorded playback.