#!/usr/bin/env python

from gnuradio import gr, gru, eng_notation
from gnuradio import audio
from gnuradio import usrp
from gnuradio import blks
from gnuradio import tv_rx
from gnuradio.eng_option import eng_option
from optparse import OptionParser
import sys
import math


"""
Reads from a file and generates PAL TV pictures in black and white
which can be displayed using ImageMagick


  # set the center freq of the TV RX tuner to 546 MHz somehow (center
  # of the 8 MHz PAL channel).  This works:

  $ tvrx_wfm_rcv_gui.py -f 546

  # adjust mux as required. This is for TV RX on B side.
  # hit Enter about 1 or 2 seconds after starting it...
  # Use a fast harddrive or ramdisk
  # -3.0 or -8.5
  # -3.75
  $ usrp_rx_cfile.py -d 8 -c -5.75M --mux=0xf0f0f0f2 -o foo.dat

  # -151.0 scale factor; 128 offset; 546  channel center freq
  $ tvrx_tv_rcv.py foo.dat 5.75 8 -151.0 128 546

  $ display -size 512x312 gray:pal_out_raw_char.gray

  # If you don't have a fast enough usb2 interface (like me)
  # You can get away with using a decimation factor of 16 like this  
  #
  $ usrp_rx_cfile.py -d 16 -c -3.75M --mux=0xf0f0f0f2 -o foo.dat
  $ tvrx_tv_rcv.py foo.dat 3.75 16 -151.0 128 546
  $ display -size 512x312 gray:pal_out_raw_char.gray
"""

#
# return a gr.flow_graph
#

def build_graph(input_filename, decimation):
    global plot
    adc_rate = 64e6
    decim = decimation #int(adc_rate/8e6)
    do_accurate=True      

    video_rate = adc_rate / decim               # 8 Mhz
    demod_rate=video_rate
    if do_accurate:
      demod_rate= video_rate*3
    fg = gr.flow_graph ()
    src = gr.file_source(gr.sizeof_char, input_filename)

    sync=gr.tv_sync(demod_rate,0)
 
    dst = gr.file_sink (gr.sizeof_char, "tv_sync.gray")#raw file with unsigned char image data,synchronized
    fg.connect (src,sync, dst)
 
    #demod_rate=sampling_freq/cfir_decimation


    return fg,demod_rate
    

def main (args):
    nargs = len (args)
    if nargs>1:
      input_filename =  sys.argv[1]   # FIXME
      decimation = int(args[1])
    else:
      input_filename="foo.gray"
      decimation=16
    print 'input_filename',input_filename
    print 'decimation',decimation

    fg,demod_rate = build_graph(input_filename, decimation)
    # insert this in your test code...
    #import os
    #print 'Blocked waiting for GDB attach (pid = %d)' % (os.getpid(),)
    #raw_input ('Press Enter to continue: ')
    # remainder of your test code follows... 
    fg.run()
    pixels_in_line_pal=demod_rate/(25*625)

    print "You can use the imagemagick display tool to show the resulting imagesequence"
    print "use the following line to show a PAL signal:"
    print "display -depth 8 -size " +str(int(pixels_in_line_pal))+ "x625  gray:tv_sync.gray"

    
if __name__ == '__main__':
    main (sys.argv[1:])

