source: svn/newcon3bcm2_21bu/nexus/app/dta/chan_mgr.c @ 26

Last change on this file since 26 was 26, checked in by phkim, 11 years ago
  1. phkim
  2. 서경방소에서 kctv 로고 변경
  • Property svn:executable set to *
File size: 133.2 KB
Line 
1/***************************************************************************
2 *     Copyright (c) 2003-2006, Broadcom Corporation
3 *     All Rights Reserved
4 *     Confidential Property of Broadcom Corporation
5 *
6 *  THIS SOFTWARE MAY ONLY BE USED SUBJECT TO AN EXECUTED SOFTWARE LICENSE
7 *  AGREEMENT  BETWEEN THE USER AND BROADCOM.  YOU HAVE NO RIGHT TO USE OR
8 *  EXPLOIT THIS MATERIAL EXCEPT SUBJECT TO THE TERMS OF SUCH AN AGREEMENT.
9 *
10 * $brcm_Workfile:  $
11 * $brcm_Revision:  $
12 * $brcm_Date: $
13 *
14 * Module Description:
15 *
16 * Revision History:
17 *
18 * $brcm_Log:  $
19 *
20 ***************************************************************************/
21
22#include "chan_mgr.h"
23#include "ts_psi.h"
24#include "ts_pat.h"
25#include "ts_pmt.h"
26#include "ts_scte_18.h"
27#include "bapp.h"
28#include "psip_ett.h"
29#include "bsettop_smessage.h"
30#include "image_recv.h"
31#include "ca_parser.h"
32#if defined(ENABLE_UMESSAGE)
33#include "umessage.h"
34#include "cmode.h"
35#endif
36
37#include "bapp_util.h"
38
39#include "ch_map.h"
40
41#ifdef  HAS_VBI
42        #include "pes_scte_127.h"
43#endif
44
45#if defined(RAM_BUILD)
46        #include "ram_header.h"
47#endif
48
49BDBG_MODULE(chan_mgr);          /* Register software module with debug interface */
50
51
52/* PR32033 fix, for ETT 10.5- 10.10, need more buffer and timeout */
53
54#define CHM_MIN(x,y)        ((x < y) ? x : y)
55
56#ifdef BDBG_DEBUG_BUILD
57static const char *s_chm_cmd_name[] = { "eCHM_CANCEL","eCHM_TUNE","eCHM_INFO","eCHM_STOP","eCHM_CHECK_SIGNAL","eCHM_HUNT","eCHM_HUNTING","eCHM_PENDING_INIT","eCHM_DOWNLOAD","eCHM_SAP"};
58#endif
59
60#define CHM_INT_STK_SIZE        1024    /* in words */
61
62#define CHM_CHECK_SIGNAL_FREQ   1000
63#define CHM_CHECK_CHMAP_FREQ    5000
64#define CHM_CHECK_PROG_FREQ             1000
65
66#define PAT_BUF_LEN         (1024 + 188)
67#define CAT_BUF_LEN         (1024 + 188)
68#define PMT_BUF_LEN         (1024 + 188)
69#define STT_BUF_LEN         (256 + 188)
70#define NIT_BUF_LEN         (4400 + 188)
71#define NTT_BUF_LEN         (4400 + 188)
72#define SVCT_BUF_LEN            (4400 + 188)
73#define EAS_BUF_LEN             (1024 + 188)
74#define EMM_BUF_LEN             (1024 + 188)
75#define CVT_BUF_LEN                     (1024 + 188)
76
77#define CHM_IDLE_TIMEOUT        30
78
79#define CAT_TIMEOUT         3000
80#define PAT_TIMEOUT         1000
81#define PMT_TIMEOUT         1000
82#define STT_TIMEOUT         1200
83#define EAS_TIMEOUT         1200
84
85/* These timeouts are for testing only and need to be adjusted to match actual system cycle times (in ms) */
86#define NIT_TIMEOUT         20000
87#define NTT_TIMEOUT         20000
88#define SVCT_TIMEOUT        35000
89#define HUNT_TIMEOUT            35000
90#define CHM_UPDATING_DELAY      4000
91
92#define CHM_DEF_VCT_ID          CONFIG_DEF_VCT_ID
93#define CHM_DEF_NETWORK_PID CONFIG_NETWORK_PID
94
95#define CHM_MUTEX_TIMEOUT   10
96#define MAX_TIME_SLOTS      4
97#define MGT_CYCLE_TIMEOUT   1           /* in seconds */
98
99#define SCTE_18_ALERT_PRIORITY          0       /* all priority */
100
101/* frequency vector is encoded in 0.25MHz increments */
102#define CHM_VECTOR_MULTIPLIER (25 * 10000)
103
104#define CHM_MIN(x,y)        ((x < y) ? x : y)
105
106#ifndef toupper
107#define toupper(x) (x&0xDF)
108#endif
109
110typedef struct iso_lang_map_t
111{
112        char            iso_lang_code[3];
113        bapp_lang_t     lang;
114}iso_lang_map_t;
115
116typedef enum chm_err_t
117{
118        eCHM_ERR_OK         = 0,
119        eCHM_ERR_FAILED     = -1,
120        eCHM_ERR_TIMEOUT    = -2,
121        eCHM_ERR_CANCELED   = -3,
122        eCHM_ERR_NO_PAT     = -4
123}chm_err_t;
124
125/* These files are in flash_install_<platform>.c and are assumed to be RAM only and
126 * are therefore not access through dispatch table.
127 */
128extern void flash_install(uint32_t base, uint32_t offset, uint8_t * data, size_t len);
129extern void chip_reset(void);
130
131static int chm_post_app_event(chm_mgr_t *p_chm,         /* Channel manager reference */
132                                                          chm_event_t *p_event  /* Event to post to app queue */
133                                                         );
134static int chm_stop_decode(chm_mgr_t *p_chm);
135static int chm_tune_freq(chm_mgr_t *p_chm,unsigned int freq_hz,unsigned int freq_idx);
136static int chm_rotate_audio(chm_mgr_t *p_chm);
137static int chm_cvt_start(chm_mgr_t *p_chm, unsigned short network_pid);
138static void chm_cvt_stop(chm_mgr_t *p_chm);
139static int chm_stt_start(chm_mgr_t *p_chm, unsigned short network_pid);
140static void chm_stt_stop(chm_mgr_t *p_chm);
141static int chm_emm_start(chm_mgr_t *p_chm, unsigned short emm_pid);
142static void chm_emm_stop(chm_mgr_t *p_chm);
143static void chm_cache_pids(chm_mgr_t *p_chm);
144static int chm_cat_start(chm_mgr_t *p_chm);
145static void chm_cat_stop(chm_mgr_t *p_chm);
146
147#ifdef  HAS_VBI
148static int chm_scte127_start(chm_mgr_t *p_chm, uint16_t scte127_pid);
149#endif
150
151bresult chm_write_software(struct image_t * image);
152
153static bool chm_check_sc(chm_mgr_t *p_chm, bband_t band, unsigned short pid);
154
155#define DBG_DUMP
156#ifdef DBG_DUMP
157static void DBG_HEXDUMP(unsigned char* ptr, unsigned long len)
158{
159        unsigned long i;
160        for (i=0; i<len; i++ )
161        {
162                if ( i % 16 == 0 )
163                        printf ("\n");
164                printf ("0x%02x, ", ptr[i]);
165        }
166        printf("\n\n");
167}
168#else
169        #define DBG_HEXDUMP(ptr, len)
170#endif
171
172/*
173Summary:
174   Get section crc.
175*/
176static inline unsigned int chm_section_crc(unsigned char *buf,size_t length)
177{
178        unsigned int crc32;
179        bapp_util_memcpy(&crc32, &(buf[length-4]),4);
180        return crc32;
181}
182
183/*
184Summary:
185        Get the current utc time in seconds.
186        Return non-zero on failure.
187*/
188
189static void chm_send_status(chm_mgr_t *p_chm,unsigned int freq, bool locked)
190{
191        bapp_tune_send_status(p_chm->tune);
192}
193
194/*
195Summary:
196        Check for a valid language code for the current language settings.
197        Returns the bapp_lang_t number or < 0 if not a valid language.
198*/
199
200static int chm_valid_lang(chm_mgr_t *p_chm,                     /* Channel manager reference */
201                                                  char *p_code    /* Three byte iso 639-2 language code */
202                                                 )
203{
204        bapp_lang_t lang = iso_639_to_lang(p_code);
205
206        BDBG_MSG(("ISO 639-2 language not found %c%c%c\n",p_code[0],p_code[1],p_code[2]));
207        return (lang == eLANG_MAX) ? eCHM_ERR_FAILED : (int)lang;
208}
209
210/*
211Summary:
212        SCTE-65 Parser Callback.
213*/
214void chm_mms_cb(NIT_MMS_RECORD *p_MMS, void *data)
215{
216        chm_mgr_t *p_chm = (chm_mgr_t *)data;
217        mms_t mms;
218
219        if (p_MMS->transmission_system != ITU_T_ANNEX_B_TX_SYS)
220        {
221                BDBG_MSG(("%s Invalid Transmission System %d\n",__FUNCTION__,p_MMS->transmission_system));
222        }
223
224        BDBG_MSG(("%s(%d,%d,%d,%d)\n",__FUNCTION__,p_MMS->idx,p_MMS->modulation_format,p_MMS->inner_coding_mode,p_MMS->symbol_rate));
225        bapp_util_memset(&mms,0,sizeof(mms_t));
226        mms.idx = p_MMS->idx;
227        mms.code_rate = p_MMS->inner_coding_mode;
228        mms.modulation = p_MMS->modulation_format;
229        p_chm->mms_flag = true;
230
231        mms.symbol_rate = p_MMS->symbol_rate;
232        ch_map_add_mms(&(p_chm->ch_map),&mms);
233
234}
235
236/*
237Summary:
238        SCTE-65 Parser Callback.
239*/
240void chm_cds_cb(unsigned int freq_khz, int idx, void *data)
241{
242        chm_mgr_t *p_chm = (chm_mgr_t *)data;
243        freq_t freq;
244
245        BDBG_MSG(("%s(%d,%d)\n",__FUNCTION__,freq_khz,idx));
246        bapp_util_memset(&freq,0,sizeof(freq_t));
247        freq.idx = idx;
248        freq.freq_khz = freq_khz;
249        ch_map_add_freq(&(p_chm->ch_map),&freq);
250
251}
252/*
253Summary:
254        SCTE-65 Parser Callback.
255*/
256void chm_sns_cb(SI_NTT_SNS_t *sns, void *data)
257{
258        chm_mgr_t *p_chm = (chm_mgr_t *)data;
259        st_t    st;
260        unsigned char code[3];
261        int len;
262        bapp_lang_t     lang = eLANG_ENGLISH; 
263
264
265        code[0] = (unsigned char)((sns->iso639 >> 16) & 0xFF);
266        code[1] = (unsigned char)((sns->iso639 >> 8) & 0xFF);
267        code[2] = (unsigned char)((sns->iso639 >> 0) & 0xFF);
268        lang = (bapp_lang_t)chm_valid_lang(p_chm,(char*)code);
269
270        if ((int)lang < 0)
271        {
272                BDBG_MSG(("INVALID ISO639 Language Code = %c%c%c\n",code[0],code[1],code[2]));
273        } else
274        {
275                BDBG_MSG(("bapp_lang_t = %d(%c%c%c)\n",lang,code[0],code[1],code[2]));
276        }
277        bapp_util_memset(&st,0,sizeof(st_t));
278
279        st.source_id = sns->source_id;
280
281        if (sns->mtt[0] != 0)
282        {
283                BDBG_WRN(("Only latin character set supported 0x%02x\n",sns->mtt[0]));
284                return;
285        }
286
287        len = sns->mtt[1];
288        if (len >= MAX_VCH_LEN)
289        {
290                len = MAX_VCH_LEN - 1;
291        }
292
293        BDBG_MSG(("name_length = %d\n",len));
294        bapp_util_memcpy(st.name,&sns->mtt[2],len);
295        st.name[len] = 0; /* null terminate string */
296        BDBG_MSG(("name = %s\n",st.name));
297        ch_map_add_st(&(p_chm->ch_map),&st);
298}
299/*
300Summary:
301        SCTE-65 Parser Callback.
302*/
303void chm_vcm_cb(SI_SVCT_VCM_CHANNEL *channel, void *data)
304{
305        chm_mgr_t *p_chm = (chm_mgr_t *)data;
306        vch_t vch;
307        bapp_t *p_app = (bapp_t*)p_chm->p_app;
308
309        bapp_util_memset(&vch,0,sizeof(vch));
310
311
312        if (channel->ChanPropUnion.mpeg_prop.prog_num == 0x0000)
313        {
314                BDBG_WRN(("%s analog program or invalid program number\n",__FUNCTION__));
315                return;
316        }
317
318        if (channel->vct_id != p_app->settings.VCT_ID)
319        {
320                BDBG_WRN(("%s SVCT VCT_ID != current VCT_ID (0x%04x != 0x%04x)\n",__FUNCTION__,channel->vct_id,p_app->settings.VCT_ID));
321                if (p_app->settings.VCT_ID != 0xFFFF)
322                {
323                        DBG_HEXDUMP(p_chm->svct_buf,16);
324                        return;
325                }
326        }
327
328        if (channel->channel_type != NORMAL_CHAN)
329        {
330                BDBG_MSG(("%s hidden - %d\n",__FUNCTION__,channel->channel_type));
331        }
332
333        vch.ch_num = channel->channum1;
334        vch.freq_idx = channel->CDS_reference;
335        vch.mms_idx = channel->ChanPropUnion.mpeg_prop.MMS_reference;
336        vch.program_num = channel->ChanPropUnion.mpeg_prop.prog_num;
337        vch.source_id = channel->source_ID;
338        vch.vchflags = channel->channel_type;
339        ch_map_add_vch(&(p_chm->ch_map),&vch);
340}
341
342/*
343Summary:
344        Check for cancel, returns true if a cancel occured.
345*/
346#ifdef BDBG_DEBUG_BUILD
347static int chm_check_cancel_ex(chm_mgr_t *p_chm ,const char* func, int line)
348        #define chm_check_cancel(chm)   chm_check_cancel_ex(chm,__FUNCTION__,__LINE__)
349#else
350static int chm_check_cancel(chm_mgr_t *p_chm )
351#endif
352{
353        chm_cmd_event_t *p_cmd;
354
355        if (p_chm->cmd == eCHM_CANCEL)
356                return 1;
357
358        p_cmd = (chm_cmd_event_t*)bapp_task_pend_event(p_chm->queue,0);
359
360        if (!p_cmd)
361                return 0;
362
363        if (p_cmd->cmd_id == eCHM_CANCEL)
364        {
365                p_chm->cmd = eCHM_CANCEL;
366                BDBG_WRN(("Command canceled(%s:%d)...\n",func,line));
367
368                /* Send message to app */
369                p_chm->chm_evt.type = eCHM_EVT_CANCEL;
370                p_chm->chm_evt.id = 0;
371                chm_post_app_event(p_chm,&p_chm->chm_evt);
372        } else
373        {
374                if (p_cmd->cmd_id == eCHM_SAP)
375                {
376                        chm_rotate_audio(p_chm);
377                } else
378                {
379                        BDBG_WRN(("Throwing away command %d(%s:%d)...\n", p_chm->cmd ,func,line));
380                }
381        }
382
383        return(p_chm->cmd == eCHM_CANCEL) ? 1 : 0;
384} 
385
386
387static void * chm_smessage_callback(void *context, size_t data_size)
388{
389        chm_mgr_t *p_chm = (chm_mgr_t *)context;
390        /* ignore return value */
391        BDBG_ERR(("%s:%d(0x%08x,%d)",__FILE__, __LINE__,context,data_size));
392        bapp_task_post_event(p_chm->gen_queue, (bapp_task_event_t)data_size);
393        return NULL;
394}
395
396static int chm_getmessage(chm_mgr_t *p_chm,     /* Channel manager reference */
397                                                  void *buf, /* buffer to copy section into */
398                                                  unsigned int *len, /* [in] max size of buffer, [out] section size copied into buffer */
399                                                  unsigned int timeout /* timeout in milliseconds */
400                                                 )
401{
402        bresult bres;
403        size_t msg_size;
404        int result = eCHM_ERR_FAILED;
405        smessage_stream_params_t params;
406
407        smessage_stream_params_init(&params, p_chm->smsg);
408        params.band = p_chm->msg_params.band;
409        params.pid = p_chm->msg_params.pid;
410        params.filter = p_chm->msg_params.filter;
411        params.buffer = buf;
412        params.buffer_size = *len;
413        params.crc_disabled = p_chm->msg_params.crc_disabled;
414        params.data_ready_callback = chm_smessage_callback;
415        params.overflow = NULL;
416        params.callback_context = (void *)p_chm;
417        params.priv = (void *)4;
418        BDBG_MSG(("pid %x fil %x tim %u len %u", params.pid, params.filter.coef[0], timeout, *len));
419        bres = smessage_start(&params, p_chm->smsg);
420        BDBG_ERR(("%s:%d-%d",__FILE__, __LINE__,bres));
421        if (b_ok != bres)
422        {
423                BDBG_ERR(("%s:%d",__FILE__, __LINE__));
424                goto ExitFunc;
425        }
426        msg_size = (size_t) bapp_task_pend_event(p_chm->gen_queue, timeout );
427        if (0 == msg_size)
428        {
429                result = eCHM_ERR_TIMEOUT;
430        } else
431        {
432                if (params.pid == 0x0000)
433                {
434                        BDBG_ERR(("%s:%d-PAT length = %d",__FILE__, __LINE__,msg_size));
435                }
436                *len = msg_size;
437                result = eCHM_ERR_OK;
438        }
439        bres = smessage_stop(p_chm->smsg);
440        if (b_ok != bres)
441        {
442                BDBG_ERR(("%s:%d",__FILE__, __LINE__));
443                result = eCHM_ERR_FAILED;
444                goto ExitFunc;
445        }
446        BDBG_ERR(("%s:%d-%d",__FILE__, __LINE__,result));
447
448        ExitFunc:
449        return result;
450}
451
452/*
453Summary:
454        Add a chanell to the channel map.
455Description:
456        Add the channel to the channel map in sorted order.
457*/
458static unsigned short s_channel_num = 100;
459static void chm_add_channel(chm_mgr_t *p_chm,           /* Channel manager reference */
460                                                        vch_t *p_vch
461                                                   )
462{
463        freq_t freq;
464        st_t  st;
465        mms_t  mms;
466
467        freq.idx = (unsigned char)p_vch->freq_idx;
468        freq.freq_khz = p_chm->freq_table[p_vch->freq_idx];
469       
470        ch_map_add_freq(&(p_chm->ch_map),&freq);
471
472        bapp_util_memset(&mms,0,sizeof(mms));
473        mms.idx = (unsigned char)p_vch->freq_idx;
474        mms.modulation = 0;
475
476        ch_map_add_mms(&(p_chm->ch_map),&mms);
477
478        p_vch->ch_num = (unsigned short)s_channel_num++;
479        p_vch->source_id = (unsigned short)p_vch->ch_num;
480        p_vch->mms_idx = (unsigned char)mms.idx;
481        ch_map_add_vch(&(p_chm->ch_map),p_vch);
482
483        st.source_id = p_vch->source_id;
484        snprintf(st.name,MAX_VCH_LEN,"Ch - %d.%d",p_vch->freq_idx + 2,p_vch->program_num);
485        ch_map_add_st(&(p_chm->ch_map),&st);
486
487}
488
489
490/*
491Summary:
492   Stop monitoring..
493*/
494void chm_nit_stop(chm_mgr_t *p_chm)
495{
496        if (NULL != p_chm->nit_msg)
497        {
498                if (b_ok != smessage_stop(p_chm->nit_msg))
499                {
500                        BDBG_ERR(("%s:%d",__FILE__, __LINE__));
501                        return;
502                }
503                smessage_close(p_chm->nit_msg);
504                p_chm->nit_msg = NULL;
505        }
506}
507
508/*
509Summary:
510   Stop monitoring..
511*/
512void chm_ntt_stop(chm_mgr_t *p_chm)
513{
514        if (NULL != p_chm->ntt_msg)
515        {
516                if (b_ok != smessage_stop(p_chm->ntt_msg))
517                {
518                        BDBG_ERR(("%s:%d",__FILE__, __LINE__));
519                        return;
520                }
521                smessage_close(p_chm->ntt_msg);
522                p_chm->ntt_msg = NULL;
523        }
524}
525
526
527/*
528Summary:
529   Stop monitoring..
530*/
531void chm_svct_stop(chm_mgr_t *p_chm)
532{
533        if (NULL != p_chm->svct_msg)
534        {
535                if (b_ok != smessage_stop(p_chm->svct_msg))
536                {
537                        BDBG_ERR(("%s:%d",__FILE__, __LINE__));
538                        return;
539                }
540                smessage_close(p_chm->svct_msg);
541                p_chm->svct_msg = NULL;
542        }
543}
544
545#ifdef  HAS_VBI
546/*
547Summary:
548   Stop SCTE 127 monitoring..
549*/
550static void chm_scte127_stop(chm_mgr_t *p_chm)
551{
552        if (NULL != p_chm->scte127_msg)
553        {
554                if (b_ok != smessage_stop(p_chm->scte127_msg))
555                {
556                        BDBG_ERR(("%s:%d",__FILE__, __LINE__));
557                        return;
558                }
559                smessage_close(p_chm->scte127_msg);
560                p_chm->scte127_msg = NULL;
561        }
562}
563#endif
564/*
565Summary:
566   Stop EAS monitoring..
567*/
568static void chm_eas_stop(chm_mgr_t *p_chm)
569{
570        if (NULL != p_chm->eas_msg)
571        {
572                if (b_ok != smessage_stop(p_chm->eas_msg))
573                {
574                        BDBG_ERR(("%s:%d",__FILE__, __LINE__));
575                        return;
576                }
577                smessage_close(p_chm->eas_msg);
578                p_chm->eas_msg = NULL;
579                p_chm->eas_timer_started = false;
580        }
581}
582
583/*
584Summary:
585   Stop CVT monitoring..
586*/
587static void chm_cvt_stop(chm_mgr_t *p_chm)
588{
589        if (NULL != p_chm->cvt_msg)
590        {
591                if (b_ok != smessage_stop(p_chm->cvt_msg))
592                {
593                        BDBG_ERR(("%s:%d",__FILE__, __LINE__));
594                        return;
595                }
596                smessage_close(p_chm->cvt_msg);
597                p_chm->cvt_msg = NULL;
598        }
599}
600/******************************************************************************
601* INPUTS:      context
602* OUTPUTS:     none.
603* RETURNS:     none
604* FUNCTION:    message_callback
605* DESCRIPTION: Callback function normally called when a complete message has
606*              been received and passed the filter criteria.
607******************************************************************************/
608
609void * chm_smessage_nit_callback(void * context, size_t size)
610{
611        chm_mgr_t * p_chm = (chm_mgr_t*)context;
612        SI_RET_CODE rc;
613        unsigned int crc32;
614        ch_map_t * p_ch_map = bapp_cur_ch_map(p_chm->p_app);
615
616        crc32 = chm_section_crc(p_chm->nit_buf,size);
617
618        p_chm->mms_flag = false;
619        if ((rc = SI_NIT_parse(p_chm->nit_buf)) != SI_SUCCESS)
620        {
621                BDBG_WRN(("NIT parse error %d\n",rc));
622        } else
623        {
624                if (p_chm->mms_flag)
625                        p_chm->mms_cnt++;
626                else
627                        p_chm->cds_cnt++;
628        }
629
630        if ((p_chm->ch_map.freq_map.num_freq > 0) && SI_NIT_CDS_Complete() && 
631                ch_map_cmp_freq(&(p_chm->ch_map.freq_map),&(p_ch_map->freq_map)))
632        {
633                p_chm->cds_changed = true;
634                BDBG_WRN(("Updated NIT-CDS\n"));
635        }
636
637        if ((p_chm->ch_map.mms_map.num_mms > 0) && SI_NIT_MMS_Complete() && 
638                ch_map_cmp_mms(&(p_chm->ch_map.mms_map),&(p_ch_map->mms_map)))
639        {
640                p_chm->mms_changed = true;
641                BDBG_WRN(("Updated NIT-MMS\n"));
642        }
643
644        return(void*)(p_chm->nit_buf);
645}
646
647/******************************************************************************
648* INPUTS:      context
649* OUTPUTS:     none.
650* RETURNS:     none
651* FUNCTION:    message_callback
652* DESCRIPTION: Callback function normally called when a complete message has
653*              been received and passed the filter criteria.
654******************************************************************************/
655
656void * chm_smessage_ntt_callback(void * context, size_t size)
657{
658        chm_mgr_t * p_chm = (chm_mgr_t*)context;
659        SI_RET_CODE rc;
660        ch_map_t * p_ch_map = bapp_cur_ch_map(p_chm->p_app);
661
662
663        BDBG_WRN(("#### NTT Event ####\n"));
664
665        if ((rc = SI_NTT_parse(p_chm->ntt_buf)) != SI_SUCCESS)
666        {
667                BDBG_WRN(("NTT parse error %d\n",rc));
668        } else
669        {
670                p_chm->sns_cnt++;
671                if ((p_chm->ch_map.st_map.num_st > 0) && SI_NTT_SNS_Complete() &&
672                        ch_map_cmp_st(&(p_chm->ch_map.st_map),&(p_ch_map->st_map)))
673                {
674                        p_chm->sns_changed = true;
675                        BDBG_WRN(("Updated NTT\n"));
676                }
677        }
678
679        return(void*)p_chm->ntt_buf;
680}
681
682/******************************************************************************
683* INPUTS:      context
684* OUTPUTS:     none.
685* RETURNS:     none
686* FUNCTION:    message_callback
687* DESCRIPTION: Callback function normally called when a complete message has
688*              been received and passed the filter criteria.
689******************************************************************************/
690
691void * chm_smessage_svct_callback(void * context, size_t size)
692{
693        chm_mgr_t * p_chm = (chm_mgr_t*)context;
694        SI_RET_CODE rc;
695        unsigned int crc32;
696        ch_map_t * p_ch_map = bapp_cur_ch_map(p_chm->p_app);
697
698        crc32 = chm_section_crc(p_chm->svct_buf,size);
699
700        BDBG_WRN(("#### SVCT Event ####\n"));
701
702        if ((rc = SI_SVCT_parse(p_chm->svct_buf)) != SI_SUCCESS)
703        {
704                BDBG_WRN(("SVCT parse error %d\n",rc));
705        } else
706        {
707                p_chm->vcm_cnt++;
708                if ((p_chm->ch_map.vch_map.num_vch > 0) && SI_SVCT_Complete() &&
709                        ch_map_cmp_vch(&(p_chm->ch_map.vch_map),&(p_ch_map->vch_map)))
710                {
711                        p_chm->vcm_changed = true;
712                        BDBG_WRN(("Updated SVCT\n"));
713                }
714        }
715
716        return(void*)p_chm->svct_buf;
717}
718
719
720/*
721Summary:
722   Start nit monitoring..
723*/
724int chm_nit_start(chm_mgr_t *p_chm, unsigned short network_pid)
725{
726        int cerr = eCHM_ERR_OK;
727        smessage_stream_params_t params;
728
729        chm_nit_stop(p_chm);
730
731        p_chm->cds_changed = false;
732        p_chm->mms_changed = false;
733        p_chm->nit_msg = smessage_open(smessage_format_psi);
734        if (NULL == p_chm->nit_msg)
735        {
736                BDBG_ERR(("%s:%d",__FILE__, __LINE__));
737                cerr = eCHM_ERR_FAILED;
738                goto ExitFunc;
739        }
740        smessage_stream_params_init(&params, p_chm->nit_msg);
741        params.band = p_chm->band;
742        params.pid = (uint16_t)network_pid;
743        params.filter.coef[0] = 0xc2;   /* Table ID for NIT */
744        params.filter.mask[0] = 0x00;
745        params.filter.excl[0] = 0xff;
746        /* All PSIP tables have protocol_version which must be = 0 */
747        params.filter.coef[3] = 0x00;   /* protocol_version */
748        params.filter.mask[3] = 0x00;
749        params.filter.excl[3] = 0xff;
750
751        params.buffer = p_chm->nit_buf;
752        params.buffer_size = NIT_BUF_LEN;
753        /* processing is done in callback */
754        params.data_ready_callback = chm_smessage_nit_callback;
755        params.overflow = NULL;
756        params.callback_context = (void *)p_chm;
757        /* Always reset the starting version numbers to work around
758           cases where headend sends new map but does not change version */
759        SI_NIT_Init (&p_chm->cds_cb,&p_chm->mms_cb,0xFF,0xFF);
760        if (b_ok != smessage_start(&params, p_chm->nit_msg))
761        {
762                BDBG_ERR(("%s:%d",__FILE__, __LINE__));
763                cerr = eCHM_ERR_FAILED;
764        }
765        ExitFunc:
766        return cerr;
767}
768/*
769Summary:
770   Start ntt monitoring..
771*/
772int chm_ntt_start(chm_mgr_t *p_chm, unsigned short network_pid)
773{
774        int cerr = eCHM_ERR_OK;
775        smessage_stream_params_t params;
776
777        chm_ntt_stop(p_chm);
778
779        p_chm->sns_changed = false;
780        p_chm->ntt_msg = smessage_open(smessage_format_psi);
781        BDBG_MSG(("%s:%d ntt_msg = 0x%08x\n",__FUNCTION__,__LINE__,p_chm->ntt_msg));
782        if (NULL == p_chm->ntt_msg)
783        {
784                BDBG_ERR(("%s:%d",__FILE__, __LINE__));
785                cerr = eCHM_ERR_FAILED;
786                goto ExitFunc;
787        }
788        smessage_stream_params_init(&params, p_chm->ntt_msg);
789        params.band = p_chm->band;
790        params.pid = (uint16_t)network_pid;
791        params.filter.coef[0] = 0xc3;   /* Table ID for NTT */
792        params.filter.mask[0] = 0x00;
793        params.filter.excl[0] = 0xff;
794        /* All PSIP tables have protocol_version which must be = 0 */
795        params.filter.coef[3] = 0x00;   /* protocol_version */
796        params.filter.mask[3] = 0x00;
797        params.filter.excl[3] = 0xff;
798
799        params.buffer = p_chm->ntt_buf;
800        params.buffer_size = NTT_BUF_LEN;
801        /* processing is done in callback */
802        params.data_ready_callback = chm_smessage_ntt_callback;
803        params.overflow = NULL;
804        /* Always reset the starting version numbers to work around
805           cases where headend sends new map but does not change version */
806        params.callback_context = (void *)p_chm;
807        SI_NTT_Init (&p_chm->sns_cb,0xFF);
808        if (b_ok != smessage_start(&params, p_chm->ntt_msg))
809        {
810                BDBG_ERR(("%s:%d",__FILE__, __LINE__));
811                cerr = eCHM_ERR_FAILED;
812        }
813        ExitFunc:
814        return cerr;
815}
816/*
817Summary:
818   Start svct monitoring..
819*/
820int chm_svct_start(chm_mgr_t *p_chm, unsigned short network_pid)
821{
822        int cerr = eCHM_ERR_OK;
823        smessage_stream_params_t params;
824        bapp_t *p_app = (bapp_t*)p_chm->p_app;
825
826        chm_svct_stop(p_chm);
827
828        p_chm->vcm_changed = false;
829        p_chm->svct_msg = smessage_open(smessage_format_psi);
830        BDBG_MSG(("%s:%d svct_msg = 0x%08x\n",__FUNCTION__,__LINE__,p_chm->svct_msg));
831        if (NULL == p_chm->svct_msg)
832        {
833                BDBG_ERR(("%s:%d",__FILE__, __LINE__));
834                cerr = eCHM_ERR_FAILED;
835                goto ExitFunc;
836        }
837        smessage_stream_params_init(&params, p_chm->svct_msg);
838        params.band = p_chm->band;
839        params.pid = (uint16_t)network_pid;
840        params.filter.coef[0] = 0xc4;   /* Table ID for SVCT */
841        params.filter.mask[0] = 0x00;
842        params.filter.excl[0] = 0xff;
843        /* All PSIP tables have protocol_version which must be = 0 */
844        params.filter.coef[3] = 0x00;   /* protocol_version */
845        params.filter.mask[3] = 0x00;
846        params.filter.excl[3] = 0xff;
847
848        params.filter.coef[4] = 0x00;   /* protocol_version */
849        params.filter.mask[4] = 0xf0;
850        params.filter.excl[4] = 0xff;
851
852        if (p_app->settings.VCT_ID != 0xFFFF)
853        {
854                /* little endian!!!! */
855                params.filter.coef[5] = (unsigned char)((p_app->settings.VCT_ID >> 8) & 0xFF);   
856                params.filter.mask[5] = 0x00;
857                params.filter.excl[5] = 0xff;
858                params.filter.coef[6] = (unsigned char)(p_app->settings.VCT_ID & 0xFF); 
859                params.filter.mask[6] = 0x00;
860                params.filter.excl[6] = 0xff;
861        }
862
863        params.buffer = p_chm->svct_buf;
864        params.buffer_size = SVCT_BUF_LEN;
865        /* processing is done in callback */
866        params.data_ready_callback = chm_smessage_svct_callback;
867        params.overflow = NULL;
868        params.callback_context = (void *)p_chm;
869        /* Always reset the starting version numbers to work around
870           cases where headend sends new map but does not change version */
871        SI_SVCT_Init (&p_chm->vcm_cb,0xFF);
872        if (b_ok != smessage_start(&params, p_chm->svct_msg))
873        {
874                BDBG_ERR(("%s:%d",__FILE__, __LINE__));
875                cerr = eCHM_ERR_FAILED;
876        }
877        ExitFunc:
878        return cerr;
879}
880
881/*
882Summary:
883        Get the program info for the program.
884Description:
885        Get the PMT for the program.
886        Returns non-zero on failure.
887*/
888
889static int chm_get_program_pid(chm_mgr_t *p_chm,                /* Channel manager reference */
890                                                           bband_t band, 
891                                                           unsigned short prog_number,
892                                                           unsigned short *PID
893                                                          )
894{
895        unsigned int section_size, pmt_section_size;
896        TS_PMT_stream pmt;
897        TS_PAT_program pat;
898        int result = eCHM_ERR_FAILED;
899        int idx,p_idx;
900
901        *PID = 0xFFFF;
902
903        smessage_stream_params_init(&p_chm->msg_params, p_chm->smsg);
904        p_chm->msg_params.band = band;
905        p_chm->msg_params.pid = (unsigned short)0;      /* PAT */
906        section_size = PAT_BUF_LEN;
907
908        if ((result = chm_getmessage(p_chm,p_chm->pat_buf,&section_size, PAT_TIMEOUT)) != 0)
909        {
910                BDBG_WRN(("Error getting PAT 0x%04x = %d\n",prog_number, result));
911                return result;
912        }
913
914        if (TS_PAT_validate(p_chm->pat_buf, section_size) != true)
915        {
916                BDBG_WRN(("TS_PAT_validate failed 0x%04x\n",prog_number));
917                return eCHM_ERR_FAILED;
918        }
919
920
921        if (TS_PAT_getNumPrograms(p_chm->pat_buf) == 0)
922        {
923                BDBG_WRN(("%s TS_PAT_getNumPrograms = 0\n",__FUNCTION__));
924                DBG_HEXDUMP(p_chm->pat_buf,section_size);
925                return eCHM_ERR_FAILED;
926        }
927
928        BDBG_WRN(("TS_PAT_getNumPrograms %d\n",TS_PAT_getNumPrograms(p_chm->pat_buf)));
929
930        for (idx = 0; idx < TS_PAT_getNumPrograms(p_chm->pat_buf); idx++)
931        {
932                if (TS_PAT_getProgram( p_chm->pat_buf, section_size, idx, &pat ) != b_ok)
933                {
934                        BDBG_WRN(("TS_PAT_validate failed 0x%04x\n",prog_number));
935                        return eCHM_ERR_FAILED;
936                }
937                BDBG_WRN(("TS_PAT_getProgram(%d,0x%04x)\n", pat.program_number,pat.PID));
938
939                if (pat.program_number != prog_number)
940                        continue;
941
942                smessage_stream_params_init(&p_chm->msg_params, p_chm->smsg);
943                p_chm->msg_params.band = band;
944                p_chm->msg_params.pid = (unsigned short)pat.PID;        /* PMT */
945                p_chm->msg_params.filter.coef[0] = 0x2;
946                p_chm->msg_params.filter.mask[0] = 0x00;
947                p_chm->msg_params.filter.excl[0] = 0xff;
948                pmt_section_size = PMT_BUF_LEN;
949                if ((result = chm_getmessage(p_chm,p_chm->pmt_buf,&pmt_section_size, PMT_TIMEOUT)) != 0)
950                {
951                        BDBG_ERR(("Error getting PAT 0x%04x\n",prog_number));
952                        return result;
953                }
954
955                for (p_idx = 0; p_idx < TS_PMT_getNumStreams(p_chm->pmt_buf,pmt_section_size); p_idx++)
956                {
957
958                        if (TS_PMT_getStream( p_chm->pmt_buf, pmt_section_size, p_idx, &pmt ) != b_ok)
959                        {
960                                BDBG_WRN(("Failure processing PMT %d\n",p_idx));
961                                return eCHM_ERR_FAILED;
962                        }
963
964                        if (pmt.stream_type == 0x0B) /* DSMCC */
965                        {
966                                BDBG_WRN(("DSMCC PID[%d] = 0x%04x\n",p_idx,pmt.elementary_PID ));
967                                *PID = pmt.elementary_PID;
968                                return eCHM_ERR_OK;
969                        } else
970                        {
971                                /* We only support the above 3 types of stream */ 
972                                BDBG_MSG(("Unsupported stream type[0x%02x]\n", pmt.stream_type ));
973                        }
974                }
975        }
976        return result;
977}
978
979/*
980Summary:
981        Get the program info for the program.
982Description:
983        Get the PMT for the program.
984        Returns non-zero on failure.
985*/
986
987static int chm_get_program(chm_mgr_t *p_chm,            /* Channel manager reference */
988                                                   vch_t *p_vch)
989{
990        unsigned int section_size, pmt_section_size;
991        TS_PMT_stream pmt;
992        TS_PAT_program pat;
993        TS_PSI_descriptor psi_desc;
994        int result = 0;
995        int idx,p_idx,desc_idx,num_prog;
996        bapp_t *p_app = (bapp_t*)p_chm->p_app;
997        unsigned int prog_ticks;
998
999        BDBG_MSG(("%s:%d\n",__FUNCTION__,__LINE__));
1000
1001        prog_ticks = bapp_task_getticks();
1002
1003        smessage_stream_params_init(&p_chm->msg_params, p_chm->smsg);
1004        p_chm->msg_params.band = p_chm->band;
1005        p_chm->msg_params.pid = (unsigned short)0;      /* PAT */
1006        section_size = PAT_BUF_LEN;
1007
1008        if ((result = chm_getmessage(p_chm,p_chm->pat_buf,&section_size, PAT_TIMEOUT)) != 0)
1009        {
1010                BDBG_WRN(("%s(%d): Error getting PAT 0x%04x = %d\n",__FUNCTION__,__LINE__,p_chm->vch.program_num, result));
1011                return result;
1012        }
1013        p_chm->pat_crc = chm_section_crc(p_chm->pat_buf,section_size);
1014        p_chm->pat_cnt++;
1015        if (TS_PAT_validate(p_chm->pat_buf, section_size) != true)
1016        {
1017                BDBG_WRN(("TS_PAT_validate failed 0x%04x\n",p_chm->vch.program_num));
1018                return eCHM_ERR_FAILED;
1019        }
1020
1021        num_prog = TS_PAT_getNumPrograms(p_chm->pat_buf);
1022        if (num_prog == 0)
1023        {
1024                BDBG_WRN(("%s TS_PAT_getNumPrograms = 0\n",__FUNCTION__));
1025                DBG_HEXDUMP(p_chm->pat_buf,section_size);
1026                return eCHM_ERR_FAILED;
1027        }
1028
1029        BDBG_MSG(("TS_PAT_getNumPrograms %d\n",num_prog));
1030
1031        for (idx = 0; idx < num_prog; idx++)
1032        {
1033                if (TS_PAT_getProgram( p_chm->pat_buf, section_size, idx, &pat ) != b_ok)
1034                {
1035                        BDBG_WRN(("TS_PAT_validate failed 0x%04x\n",idx));
1036                        return eCHM_ERR_FAILED;
1037                }
1038
1039                BDBG_MSG(("TS_PAT_getProgram(%d,0x%04x)\n", pat.program_number,pat.PID));
1040
1041                /* Check for new network PID */
1042                if (pat.program_number == 0)
1043                {
1044                        if (pat.PID != p_app->settings.network_PID)
1045                        {
1046                                p_chm->network_pid = pat.PID;
1047                        }
1048                }
1049
1050                if (p_chm->vch.program_num != pat.program_number)
1051                        continue;
1052
1053                p_vch->num_audio = 0;
1054                p_vch->cur_audio = 0;
1055                p_vch->pcr_pid = 0;
1056                p_vch->video_pid = 0;
1057                p_vch->scte127_pid = 0;
1058                p_vch->audio_pid[0] = 0;
1059
1060                smessage_stream_params_init(&p_chm->msg_params, p_chm->smsg);
1061                p_chm->msg_params.band = p_chm->band;
1062                p_chm->msg_params.pid = (unsigned short)pat.PID;        /* PMT */
1063                p_chm->msg_params.filter.coef[0] = 0x2;
1064                p_chm->msg_params.filter.mask[0] = 0x00;
1065                p_chm->msg_params.filter.excl[0] = 0xff;
1066                pmt_section_size = PMT_BUF_LEN;
1067                if ((result = chm_getmessage(p_chm,p_chm->pmt_buf,&pmt_section_size, PMT_TIMEOUT)) != 0)
1068                {
1069                        BDBG_ERR(("%s(%d): Error getting PAT 0x%04x = %d\n",__FUNCTION__,__LINE__,p_chm->vch.program_num, result));
1070                        return result;
1071                }
1072                p_chm->pmt_crc = chm_section_crc(p_chm->pmt_buf,pmt_section_size);
1073
1074                p_chm->pmt_cnt++;
1075
1076                p_vch->pcr_pid = TS_PMT_getPcrPid(p_chm->pmt_buf,pmt_section_size);
1077
1078                /* Get CA pid */
1079                desc_idx = 0;
1080                p_vch->ca_pid = 0;
1081                while ((psi_desc = TS_PMT_getDescriptor(p_chm->pmt_buf, pmt_section_size,desc_idx++)) != NULL)
1082                {
1083                        static ca_descriptor ca_desc;
1084                        if (desc_idx > 0xFF)
1085                        {
1086                                BDBG_ERR(("PMT Desc limit exceeded %d\n",desc_idx));
1087                                break;
1088                        }
1089                        if (chm_check_cancel(p_chm))
1090                        {
1091                                return eCHM_ERR_CANCELED;
1092                        }
1093
1094                        if (psi_desc[0] != 9)
1095                                continue;
1096
1097                        if (ca_parser(psi_desc, pmt_section_size, &ca_desc) == 0)
1098                                continue;
1099
1100                        if (ca_desc.CA_system_ID == p_app->settings.CA_System_ID)
1101                        {
1102                                p_vch->ca_pid = ca_desc.CA_PID;
1103                                BDBG_WRN(("CA PID = 0x%04x\n",p_vch->ca_pid));
1104                                p_app->settings.SCP_operating_mode = 0;
1105                                if (ca_desc.CA_system_ID == 0x0E11)
1106                                {
1107                                        /* Send message to app */
1108                                        if ((ca_desc.priv_data[0] == 0x5) && (ca_desc.priv_data[1] == 0x1))
1109                                                p_app->settings.SCP_operating_mode = ca_desc.priv_data[2];
1110                                }
1111                                break;
1112                        }
1113                        else
1114                        {
1115                                p_chm->system_id_errors++;
1116                        }
1117
1118                }
1119
1120                for (p_idx = 0; p_idx < TS_PMT_getNumStreams(p_chm->pmt_buf,pmt_section_size); p_idx++)
1121                {
1122                        TS_PSI_descriptor psi_desc,lang_desc;
1123                        int strm_idx;
1124                        bapp_av_stream_type_t *stream_type;
1125
1126                        if (TS_PMT_getStream( p_chm->pmt_buf, pmt_section_size, p_idx, &pmt ) != b_ok)
1127                        {
1128                                BDBG_WRN(("Failure processing PMT %d\n",p_idx));
1129                                return eCHM_ERR_FAILED;
1130                        }
1131
1132                        strm_idx = 0;
1133                        lang_desc = NULL;
1134                        /* default is not supported */
1135                        while ((psi_desc = TS_PMT_getStreamDescriptor(p_chm->pmt_buf,pmt_section_size, p_idx,strm_idx)) != NULL)
1136                        {
1137                                if (psi_desc[0] == TS_PSI_DT_ISO_639_Language) /* 0x0A ISO-639 Language descriptor */
1138                                {
1139                                        BDBG_MSG(("ISO-639 DESC\n" ));
1140                                        lang_desc = psi_desc;
1141                                        /* if get VBI desc alrady */
1142                                        if (p_vch->scte127_pid)
1143                                                break;
1144                                }
1145                                if (0 == p_vch->scte127_pid)
1146                                {
1147                                        if (TS_PSI_DT_DVB_VBI_Data == psi_desc[0])
1148                                        {
1149                                                BDBG_MSG(("SCTE 127 supported, pid=0x%04x", pmt.elementary_PID));
1150                                                p_vch->scte127_pid = pmt.elementary_PID;
1151                                                /* if get lang desc alrady */
1152                                                if (lang_desc)
1153                                                        break;
1154                                        }
1155                                }
1156                                strm_idx++;
1157                                if (strm_idx > 0xFF)
1158                                {
1159                                        BDBG_ERR(("PMT Stream Desc limit exceeded %d\n",strm_idx));
1160                                        break;
1161                                }
1162                                if (chm_check_cancel(p_chm))
1163                                {
1164                                        return eCHM_ERR_CANCELED;
1165                                }
1166                        }
1167
1168                        if ((stream_type = bapp_av_supported_video(pmt.stream_type)) != NULL)
1169                        {
1170                                BDBG_WRN(("Video PID[%d] = 0x%04x\n",p_idx,pmt.elementary_PID ));
1171                                if (!p_vch->video_pid)
1172                                {
1173                                        p_vch->video_pid = pmt.elementary_PID;
1174                                        p_vch->video_type = stream_type->codec_id;
1175                                }
1176                        }
1177                        else if ((stream_type = bapp_av_supported_audio(pmt.stream_type)) != NULL)
1178                        {
1179                                BDBG_WRN(("Audio PID[%d] = 0x%04x\n",p_vch->num_audio,pmt.elementary_PID ));
1180                                if (!p_vch->audio_pid[p_vch->num_audio])
1181                                {
1182                                        p_vch->audio_pid[p_vch->num_audio] = pmt.elementary_PID;
1183                                        p_vch->audio_type[p_vch->num_audio] = stream_type->codec_id;
1184                                        if (lang_desc)
1185                                        {
1186                                                p_vch->audio_lang[p_vch->num_audio][0] = toupper(lang_desc[2]);
1187                                                p_vch->audio_lang[p_vch->num_audio][1] = toupper(lang_desc[3]);
1188                                                p_vch->audio_lang[p_vch->num_audio][2] = toupper(lang_desc[4]);
1189                                        }
1190                                        p_vch->num_audio++;
1191                                }
1192                        }
1193                        else
1194                        {
1195                                BDBG_WRN(("Unsupported stream type[0x%02x]\n", pmt.stream_type));
1196                        }
1197                }
1198        }
1199
1200        prog_ticks = bapp_task_getticks() - prog_ticks;
1201        p_chm->status_evt.type = eCHM_EVT_STATUS;
1202        p_chm->status_evt.id = eCHM_STATUS_SI_MS;
1203        p_chm->status_evt.ticks = TICKS_TO_MS(prog_ticks);
1204        chm_post_app_event(p_chm,&p_chm->status_evt);
1205
1206
1207        return result;
1208}
1209/*
1210Summary:
1211        Scan for channels using PSI.
1212Description:
1213        Scan for channels using PSI.
1214        Returns number of channels added.
1215*/
1216
1217static int chm_scan_psi(chm_mgr_t *p_chm,               /* Channel manager reference */
1218                                                bband_t band, int freq_idx)
1219{
1220        unsigned int section_size, pmt_section_size;
1221        TS_PMT_stream pmt;
1222        TS_PAT_program pat;
1223        int result = 0;
1224        int idx,p_idx,tresult, desc_idx;
1225        vch_t vch;
1226        TS_PSI_descriptor psi_desc;
1227        unsigned short ca_pid = 0;
1228
1229        bapp_util_memset(&vch,0,sizeof(vch));
1230
1231        /* Get the PAT */
1232        smessage_stream_params_init(&p_chm->msg_params, p_chm->smsg);
1233        p_chm->msg_params.band = band;
1234        p_chm->msg_params.pid = (unsigned short)0;      /* PAT */
1235        section_size = PAT_BUF_LEN;
1236
1237        if ((result = chm_getmessage(p_chm,p_chm->pat_buf,&section_size, PAT_TIMEOUT)) != 0)
1238        {
1239                BDBG_WRN(("%s Timeout getting PAT section_size = %d\n",__FUNCTION__,section_size));
1240                return result;
1241        }
1242        BDBG_WRN(("%s:%d section_size = %d\n",__FUNCTION__,__LINE__,section_size));
1243        p_chm->pat_crc = chm_section_crc(p_chm->pat_buf,section_size);
1244
1245        BDBG_WRN(("%s:%d section_size = %d\n",__FUNCTION__,__LINE__,section_size));
1246        if (TS_PAT_validate(p_chm->pat_buf, section_size) != true)
1247        {
1248                BDBG_WRN(("TS_PAT_validate failed\n"));
1249                return eCHM_ERR_FAILED;
1250        }
1251        BDBG_WRN(("%s:%d section_size = %d\n",__FUNCTION__,__LINE__,section_size));
1252
1253        BDBG_WRN(("Programs %d\n",TS_PAT_getNumPrograms(p_chm->pat_buf)));
1254
1255        if (TS_PAT_getNumPrograms(p_chm->pat_buf) == 0)
1256        {
1257                BDBG_WRN(("%s TS_PAT_getNumPrograms = 0,section_size = %d\n",__FUNCTION__,section_size));
1258                DBG_HEXDUMP(p_chm->pat_buf,section_size);
1259                return eCHM_ERR_FAILED;
1260        }
1261
1262        for (idx = 0; idx < TS_PAT_getNumPrograms(p_chm->pat_buf); idx++)
1263        {
1264                BDBG_WRN(("PMT_PID = 0x%04x\n",pat.PID));
1265
1266                if (chm_check_cancel(p_chm))
1267                {
1268                        return eCHM_ERR_CANCELED;
1269                }
1270
1271                bapp_util_memset(&vch,0,sizeof(vch));
1272                section_size = PAT_BUF_LEN;
1273                if (TS_PAT_getProgram( p_chm->pat_buf, section_size, idx, &pat ) != b_ok)
1274                {
1275                        BDBG_WRN(("TS_PAT_validate failed 0x%04x\n",pat.PID));
1276                        return eCHM_ERR_FAILED;
1277                }
1278
1279                smessage_stream_params_init(&p_chm->msg_params, p_chm->smsg);
1280                p_chm->msg_params.band = band;
1281                p_chm->msg_params.pid = (unsigned short)pat.PID;        /* PMT */
1282                p_chm->msg_params.filter.coef[0] = 0x2;
1283                p_chm->msg_params.filter.mask[0] = 0x00;
1284                p_chm->msg_params.filter.excl[0] = 0xff;
1285                pmt_section_size = PMT_BUF_LEN;
1286                if ((tresult = chm_getmessage(p_chm,p_chm->pmt_buf,&pmt_section_size, PMT_TIMEOUT)) != 0)
1287                {
1288                        BDBG_WRN(("Failed getting PMT 0x%04x\n",pat.PID));
1289                        continue;
1290                }
1291                p_chm->pmt_crc = chm_section_crc(p_chm->pmt_buf,pmt_section_size);
1292
1293                vch.freq_idx = freq_idx;
1294                vch.pcr_pid = TS_PMT_getPcrPid(p_chm->pmt_buf,pmt_section_size);
1295                ca_pid = 0;
1296                vch.program_num = pat.program_number;
1297                /* Get CA pid for cable */
1298                desc_idx = 0;
1299                while ((psi_desc = TS_PMT_getDescriptor(p_chm->pmt_buf, pmt_section_size,desc_idx++)) != NULL)
1300                {
1301                        if (desc_idx > 0xFF)
1302                        {
1303                                BDBG_ERR(("PMT Desc limit exceeded %d\n",desc_idx));
1304                                break;
1305                        }
1306                        if (chm_check_cancel(p_chm))
1307                        {
1308                                return eCHM_ERR_CANCELED;
1309                        }
1310                        if (psi_desc[0] == 9)
1311                        {
1312                                ca_pid = (((unsigned short)(psi_desc[4] & 0x1F)) << 8) | (unsigned short)psi_desc[5];
1313                                BDBG_WRN(("CA PID = 0x%04x\n",ca_pid));
1314                                break;
1315                        }
1316                }
1317                if (ca_pid != 0x0000)
1318                {
1319                        BDBG_WRN(("Program has CA PID 0x%02x check for scrambling control bit.\n",ca_pid));
1320                        vch.ca_pid = ca_pid;
1321                }
1322
1323                BDBG_WRN(("Streams = %d\n",TS_PMT_getNumStreams(p_chm->pmt_buf,pmt_section_size)));
1324                for (p_idx = 0; p_idx < TS_PMT_getNumStreams(p_chm->pmt_buf,pmt_section_size); p_idx++)
1325                {
1326                        bapp_av_stream_type_t *stream_type;
1327                        if (TS_PMT_getStream( p_chm->pmt_buf, pmt_section_size, p_idx, &pmt ) != b_ok)
1328                        {
1329                                BDBG_WRN(("Failure processing PMT %d\n",p_idx));
1330                                return eCHM_ERR_FAILED;
1331                        }
1332
1333                        if ((stream_type = bapp_av_supported_video(pmt.stream_type)) != NULL)
1334                        {
1335                                BDBG_WRN(("Video PID[%d] = 0x%04x\n",p_idx,pmt.elementary_PID ));
1336                                if (!vch.video_pid)
1337                                {
1338                                        vch.video_pid = pmt.elementary_PID;
1339                                        vch.video_type = stream_type->codec_id;
1340                                }
1341                        }
1342                        else if ((stream_type = bapp_av_supported_audio(pmt.stream_type)) != NULL)
1343                        {
1344                                BDBG_WRN(("Audio PID[%d] = 0x%04x\n",vch.num_audio,pmt.elementary_PID ));
1345                                if (!vch.audio_pid[vch.num_audio])
1346                                {
1347                                        vch.audio_pid[vch.num_audio] = pmt.elementary_PID;
1348                                        vch.audio_type[vch.num_audio] = stream_type->codec_id;
1349                                        vch.num_audio++;
1350                                }
1351                        }
1352                }
1353
1354                if ((vch.video_pid) || (vch.audio_pid[0]))
1355                {
1356                        bool clear = true;;
1357                        unsigned short pid;
1358                        if (vch.video_pid)
1359                                pid = (unsigned short)vch.video_pid;
1360                        else
1361                                pid     = (unsigned short)vch.audio_pid[0];
1362                        /* correct pid in case video pid carries too few frames */
1363                        if(vch.pcr_pid == vch.audio_pid[0])
1364                                pid = (unsigned short)vch.audio_pid[0];
1365
1366                        if (vch.ca_pid != 0x0000)
1367                                clear = chm_check_sc(p_chm, band, pid);
1368                        else
1369                                clear = 1;
1370
1371                        if (clear)
1372                        {
1373                                p_chm->chm_pat_evt.type = eCHM_EVT_STATUS;
1374                                p_chm->chm_pat_evt.id = eCHM_STATUS_PAT;
1375                                chm_post_app_event(p_chm,&p_chm->chm_pat_evt);
1376                                chm_add_channel(p_chm,&vch);
1377                                result += 1;
1378                        }
1379                }
1380        }
1381
1382        return result;
1383}
1384
1385/*
1386Summary:
1387        Stop the STT. return non-zero on failure
1388*/
1389static void chm_stt_stop(chm_mgr_t *p_chm)
1390{
1391        if (NULL != p_chm->stt_msg)
1392        {
1393                BDBG_WRN(("%s\n",__FUNCTION__));
1394                if (b_ok != smessage_stop(p_chm->stt_msg))
1395                {
1396                        BDBG_ERR(("%s:%d",__FUNCTION__, __LINE__));
1397                        return;
1398                }
1399                smessage_close(p_chm->stt_msg);
1400                p_chm->stt_msg = NULL;
1401        }
1402}
1403
1404/*
1405Summary:
1406        Scan for channels to create a channel map.
1407Description:
1408        Scan for all available channels.
1409*/
1410
1411static void chm_stream_close(chm_mgr_t *p_chm           /* Channel manager reference */
1412                                                        )
1413{
1414}
1415/*
1416Summary:
1417        Callback function normally called when a complete message has
1418        been received and passed the filter criteria.
1419 */
1420bool found_system = false;
1421static void * chm_smessage_cat_callback(void * context, size_t section_size)
1422{
1423        chm_mgr_t * p_chm = (chm_mgr_t*)context;
1424        unsigned int len = section_size;
1425        unsigned char *ptr;
1426        ca_descriptor ca_desc;
1427        found_system = false;
1428        p_chm->cat_cnt++;
1429        BDBG_WRN(("%s %d\n",__FUNCTION__,section_size));
1430
1431        if ((ptr = cat_parser(p_chm->cat_buf, &len)) != NULL)
1432        {
1433                while ((len > 9) && ptr)
1434                {          /* 6 + 4 for CRC */
1435                        if (ca_parser(ptr, len, &ca_desc) != 0)
1436                        {
1437                                ptr += ca_desc.priv_length + 6;
1438                                len -= (ca_desc.priv_length + 6);
1439                                BDBG_WRN(("%s CA_System_ID = 0x%04x, EMM_PID = 0x%04x.\n",__FUNCTION__,
1440                                                  ca_desc.CA_system_ID,ca_desc.CA_PID));
1441                                if ((ca_desc.CA_system_ID == 0x4749) || (ca_desc.CA_system_ID == 0x0E11))
1442                                {
1443                                        /* Send message to app */
1444                                        chm_ca_event_t *p_ca_evt = (chm_ca_event_t*)&p_chm->ca_evt;
1445                                        p_ca_evt->type = eCHM_EVT_CA;
1446                                        p_ca_evt->CA_System_ID = ca_desc.CA_system_ID;
1447                                        p_ca_evt->EMM_Provider_ID = 0;
1448                                        p_ca_evt->SCP_operating_mode = 0;
1449                                        if (ca_desc.CA_system_ID == 0x4749)
1450                                                p_ca_evt->EMM_Provider_ID = (unsigned short)ca_desc.priv_data[0] | ((unsigned short)ca_desc.priv_data[1] << 8);
1451                                        else if ((ca_desc.CA_system_ID == 0x0E11) && (ca_desc.priv_data[0] == 0x5) && (ca_desc.priv_data[1] == 0x1))
1452                                                p_ca_evt->SCP_operating_mode = ca_desc.priv_data[2];
1453
1454                                        p_ca_evt->EMM_PID = ca_desc.CA_PID;
1455                                        p_ca_evt->freq_khz = p_chm->last_freq_hz;
1456                                        chm_post_app_event(p_chm,(chm_event_t*)p_ca_evt);
1457                    found_system = true;
1458                                } else
1459                                {
1460                                        p_chm->system_id_errors++;
1461                                        BDBG_WRN(("INVALID CA SYSTEM 0x%04x\n",ca_desc.CA_system_ID));
1462                                }
1463                        } else
1464                        {
1465                                BDBG_WRN(("%s ca_parse failed.\n",__FUNCTION__));
1466                                break;
1467                        }
1468                }
1469        } else
1470        {
1471                BDBG_WRN(("%s Timeout getting CAT\n",__FUNCTION__));
1472        }
1473        return p_chm->cat_buf;
1474}
1475/*
1476Summary:
1477Start CAT monitoring..
1478 */
1479static int chm_cat_start(chm_mgr_t *p_chm)
1480{
1481        int cerr = eCHM_ERR_OK;
1482        smessage_stream_params_t params;
1483
1484        chm_cat_stop(p_chm);
1485
1486        p_chm->cat_msg = smessage_open(smessage_format_psi);
1487        if (NULL == p_chm->cat_msg)
1488        {
1489                BDBG_ERR(("%s:%d",__FILE__, __LINE__));
1490                cerr = eCHM_ERR_FAILED;
1491                goto ExitFunc;
1492        }
1493        smessage_stream_params_init(&params, p_chm->cat_msg);
1494        params.band = p_chm->band;
1495        params.pid = 1;
1496        params.buffer = p_chm->cat_buf;
1497        params.buffer_size = CAT_BUF_LEN;
1498        params.data_ready_callback = chm_smessage_cat_callback;
1499        params.overflow = NULL;
1500        params.callback_context = (void *)p_chm;
1501
1502        if (b_ok != smessage_start(&params, p_chm->cat_msg))
1503        {
1504                BDBG_ERR(("%s:%d",__FILE__, __LINE__));
1505                cerr = eCHM_ERR_FAILED;
1506        }
1507
1508        ExitFunc:
1509        return cerr;
1510}
1511
1512/*
1513Summary:
1514   Stop CAT monitoring..
1515*/
1516static void chm_cat_stop(chm_mgr_t *p_chm)
1517{
1518        if (NULL != p_chm->cat_msg)
1519        {
1520                if (b_ok != smessage_stop(p_chm->cat_msg))
1521                {
1522                        BDBG_ERR(("%s:%d",__FILE__, __LINE__));
1523                        return;
1524                }
1525                smessage_close(p_chm->cat_msg);
1526                p_chm->cat_msg = NULL;
1527        }
1528}
1529
1530/*
1531Summary:
1532        Scan for the CAT/CA descriptor.
1533Description:
1534        Scan for the CAT/CA descriptor.
1535        Returns non-zero on error.
1536 */
1537
1538static int chm_scan_cat(chm_mgr_t *p_chm,               /* Channel manager reference */
1539                                                bband_t band,
1540                                                unsigned int freq_khz)
1541{
1542        unsigned int section_size;
1543        int result = eCHM_ERR_FAILED;
1544
1545        /* Get the VCT */
1546        smessage_stream_params_init(&p_chm->msg_params, p_chm->smsg);
1547        p_chm->msg_params.band = band;
1548        p_chm->msg_params.pid = (unsigned short)1;      /* CAT */
1549        section_size = CAT_BUF_LEN;
1550
1551        if ((result = chm_getmessage(p_chm,p_chm->cat_buf,&section_size, CAT_TIMEOUT)) != 0)
1552        {
1553                BDBG_WRN(("%s Timeout getting CAT\n",__FUNCTION__));
1554                return result;
1555        }
1556
1557        chm_smessage_cat_callback(p_chm,section_size);
1558        result = (found_system) ? eCHM_ERR_OK : eCHM_ERR_FAILED;
1559
1560        return result;
1561}
1562
1563#if 0
1564
1565/*
1566Summary:
1567        Scan for the CAT/CA descriptor.
1568Description:
1569        Scan for the CAT/CA descriptor.
1570        Returns non-zero on error.
1571*/
1572
1573static int chm_scan_cat(chm_mgr_t *p_chm,               /* Channel manager reference */
1574                                                bband_t band,
1575                                                unsigned int freq_khz)
1576{
1577        unsigned int section_size,len;
1578        unsigned char *ptr;
1579        static ca_descriptor ca_desc;
1580        int result = eCHM_ERR_FAILED;
1581        bapp_t *p_app = (bapp_t*)p_chm->p_app;
1582
1583        /* Get the VCT */
1584        smessage_stream_params_init(&p_chm->msg_params, p_chm->smsg);
1585        p_chm->msg_params.band = band;
1586        p_chm->msg_params.pid = (unsigned short)1;      /* CAT */
1587        section_size = CAT_BUF_LEN;
1588
1589        if ((result = chm_getmessage(p_chm,p_chm->cat_buf,&section_size, CAT_TIMEOUT)) != 0)
1590        {
1591                BDBG_WRN(("%s Timeout getting CAT\n",__FUNCTION__));
1592                return result;
1593        }
1594
1595        p_chm->cat_cnt++;
1596        if ((ptr = cat_parser(p_chm->cat_buf, &len)) != NULL)
1597        {
1598                while ((len > 9) && ptr)
1599                {          /* 6 + 4 for CRC */
1600                        if (ca_parser(ptr, len, &ca_desc))
1601                        {
1602                                ptr += ca_desc.priv_length + 6;
1603                                len -= (ca_desc.priv_length + 6);
1604
1605                                BDBG_WRN(("%s CA_System_ID = 0x%04x, EMM_PID = 0x%04x.\n",__FUNCTION__,
1606                                                  ca_desc.CA_system_ID,ca_desc.CA_PID));
1607
1608                                if (freq_khz == 0)
1609                                {
1610                                        if (ca_desc.CA_system_ID != p_app->settings.CA_System_ID)
1611                                        {
1612                                                p_chm->system_id_errors++;
1613                                        }
1614                                }
1615                                else
1616                                {
1617                                        if ((ca_desc.CA_system_ID == 0x4749) || (ca_desc.CA_system_ID == 0x0E11))
1618                                        {
1619                                                /* Send message to app */
1620                                                chm_ca_event_t *p_ca_evt = (chm_ca_event_t*)&p_chm->ca_evt;
1621                                                p_ca_evt->type = eCHM_EVT_CA;
1622                                                p_ca_evt->CA_System_ID = ca_desc.CA_system_ID;
1623                                                p_ca_evt->EMM_Provider_ID = 0;
1624                                                p_ca_evt->SCP_operating_mode = 0;
1625                                                if (ca_desc.CA_system_ID == 0x4749)
1626                                                        p_ca_evt->EMM_Provider_ID = (unsigned short)ca_desc.priv_data[0] | ((unsigned short)ca_desc.priv_data[1] << 8);
1627                                                else if ((ca_desc.CA_system_ID == 0x0E11) && (ca_desc.priv_data[0] == 0x5) && (ca_desc.priv_data[1] == 0x1))
1628                                                        p_ca_evt->SCP_operating_mode = ca_desc.priv_data[2];
1629
1630                                                p_ca_evt->EMM_PID = ca_desc.CA_PID;
1631                                                p_ca_evt->freq_khz = freq_khz;
1632                                                chm_post_app_event(p_chm,(chm_event_t*)p_ca_evt);
1633                                                result = eCHM_ERR_OK;
1634                                        } else
1635                                        {
1636                                                p_chm->system_id_errors++;
1637                                                BDBG_WRN(("INVALID CA SYSTEM 0x%04x\n",ca_desc.CA_system_ID));
1638                                        }
1639                                }
1640
1641                        } else
1642                        {
1643                                BDBG_WRN(("%s ca_parse failed.\n",__FUNCTION__));
1644                                result = eCHM_ERR_FAILED;
1645                                break;
1646                        }
1647                }
1648        } else
1649        {
1650                BDBG_WRN(("%s Timeout getting CAT\n",__FUNCTION__));
1651        }
1652
1653
1654        return result;
1655}
1656#endif
1657/*
1658Summary:
1659        Scan for the network PID.
1660Description:
1661        Scan for the network PID in pat PMT with program id 0.
1662        Returns the network PID.
1663*/
1664
1665static int chm_scan_network(chm_mgr_t *p_chm,           /* Channel manager reference */
1666                                                        bband_t band, 
1667                                                        unsigned short *network_PID)
1668{
1669        unsigned int section_size;
1670        TS_PAT_program pat;
1671        int result = eCHM_ERR_FAILED;
1672        int idx;
1673        BDBG_WRN(("%s:%d\n",__FUNCTION__,__LINE__));
1674
1675        *network_PID = CHM_DEF_NETWORK_PID;     /* Default PID value for this network */
1676
1677        /* Get the VCT */
1678        smessage_stream_params_init(&p_chm->msg_params, p_chm->smsg);
1679        p_chm->msg_params.band = band;
1680        p_chm->msg_params.pid = (unsigned short)0;      /* PAT */
1681        section_size = PAT_BUF_LEN;
1682
1683        if ((result = chm_getmessage(p_chm,p_chm->pat_buf,&section_size, PAT_TIMEOUT)) != 0)
1684        {
1685                BDBG_WRN(("%s Timeout getting PAT\n",__FUNCTION__));
1686                return result;
1687        }
1688        if (TS_PAT_validate(p_chm->pat_buf, section_size) != true)
1689        {
1690                BDBG_WRN(("TS_PAT_validate failed\n"));
1691                return eCHM_ERR_FAILED;
1692        }
1693        p_chm->pat_cnt++;
1694        BDBG_WRN(("%s:%d\n",__FUNCTION__,__LINE__));
1695
1696        for (idx = 0; idx < TS_PAT_getNumPrograms(p_chm->pat_buf); idx++)
1697        {
1698                if (chm_check_cancel(p_chm))
1699                {
1700                        return eCHM_ERR_CANCELED;
1701                }
1702
1703                section_size = PAT_BUF_LEN;
1704                if (TS_PAT_getProgram( p_chm->pat_buf, section_size, idx, &pat ) != b_ok)
1705                {
1706                        BDBG_WRN(("TS_PAT_validate failed 0x%04x\n",pat.PID));
1707                        return eCHM_ERR_FAILED;
1708                }
1709                p_chm->pmt_cnt++;
1710                BDBG_WRN(("TS_PAT_getProgram %d PID 0x%04x\n",pat.program_number,pat.PID));
1711
1712                if (pat.program_number == 0 )
1713                {
1714                        *network_PID = pat.PID;
1715                        /* Send message to app */
1716                        p_chm->chm_network_evt.type = eCHM_EVT_NETWORK;
1717                        p_chm->chm_network_evt.id = *network_PID;
1718                        chm_post_app_event(p_chm,&p_chm->chm_network_evt);
1719                }
1720        }
1721
1722        return result;
1723}
1724/*
1725Summary:
1726        Return the hunt mode progress in percent.
1727 */
1728
1729int chm_get_hunt_progress(chm_mgr_t *p_chm)
1730{
1731        bapp_t *p_app = (bapp_t*)p_chm->p_app;
1732        int total;
1733
1734        if (p_chm->num_freq == 0)
1735        {
1736                bapp_freq_table_get(p_chm->fe_type,(const unsigned int **)&(p_chm->freq_table),&(p_chm->num_freq));
1737        }
1738
1739        if (p_chm->num_freq == 0)
1740        {
1741                BDBG_WRN(("%s:%d p_chm->num_freq = %d\n",__FUNCTION__,__LINE__,p_chm->num_freq));
1742                return 0;
1743        }
1744        total = p_chm->num_freq;
1745
1746        if (p_chm->cmd == eCHM_HUNTING)
1747        {
1748                if ((p_chm->hunt_cnt + 1) % 2)
1749                        total *= 2;
1750        }
1751               
1752        return (p_chm->select_idx * 100)/total;
1753
1754}
1755
1756
1757/*
1758Summary:
1759        Scan for channels to create a channel map.
1760Description:
1761        Scan for all available channels.
1762*/
1763
1764static void chm_scan(chm_mgr_t *p_chm           /* Channel manager reference */
1765                                        )
1766{
1767        unsigned int freq;
1768        int num;
1769
1770        bapp_freq_table_get(p_chm->fe_type,(const unsigned int **)&(p_chm->freq_table),&(p_chm->num_freq));
1771
1772        for (p_chm->select_idx = 0; p_chm->select_idx <  p_chm->num_freq; p_chm->select_idx++)
1773        {
1774                freq = (unsigned int)(p_chm->freq_table[p_chm->select_idx]);
1775                freq *= 1000; /* convert to Hz */
1776                BDBG_WRN(("Scan[%d] freq = %d\n",p_chm->select_idx,freq));
1777
1778                /* Check to see if scan was canceled */
1779                if (chm_check_cancel(p_chm))
1780                        break;
1781
1782                /* output progress event id will be % done */
1783                p_chm->chm_pat_evt.type = eCHM_EVT_STATUS;
1784                p_chm->chm_pat_evt.id = eCHM_STATUS_NOPAT;
1785                chm_post_app_event(p_chm,&p_chm->chm_pat_evt);
1786
1787                /* Try tuning */
1788                if (bapp_tune_lock(p_chm->tune,freq) != eBAPP_RESULT_OK)
1789                {
1790                        chm_send_status(p_chm,freq,false);
1791                        continue;
1792                }
1793                BDBG_WRN(("btuner_tune_xxx[%d] freq = %d, success\n",p_chm->select_idx,freq));
1794                chm_send_status(p_chm,freq,true);
1795
1796        if ((num = chm_scan_psi(p_chm,p_chm->band,p_chm->select_idx)) <= 0)
1797                {
1798                        BDBG_WRN(("chm_scan_psi found no channels\n"));
1799                } else
1800                {
1801                        BDBG_MSG(("PSI channels %d \n", num));
1802                }
1803        }
1804}
1805
1806/*
1807Summary:
1808        Scan for channels using SCTE 65.
1809Description:
1810        Scan for channels SCTE 65.
1811        Returns number of channels added.
1812*/
1813static int chm_scan_scte65(chm_mgr_t *p_chm,            /* Channel manager reference */
1814                                                   bband_t band, 
1815                                                   unsigned short network_PID
1816                                                  )
1817{
1818        unsigned short num_vch, num_st;
1819        unsigned char num_freq ;
1820        unsigned int timeout;
1821        bool done = false;
1822        timeout = bapp_task_getticks() + MS_TO_TICKS(HUNT_TIMEOUT);
1823        BDBG_MSG(("%s Network PID = 0x%04x\n",__FUNCTION__,network_PID));
1824
1825        /* scan for SCTE 65 tables */
1826        if (chm_nit_start(p_chm,network_PID) != eCHM_ERR_OK)
1827                return eCHM_ERR_FAILED;
1828        if (p_chm->cmd != eCHM_HUNTING)
1829        {
1830                if (chm_svct_start(p_chm,network_PID) != eCHM_ERR_OK)
1831                        return eCHM_ERR_FAILED;
1832                if (chm_ntt_start(p_chm,network_PID) != eCHM_ERR_OK)
1833                        return eCHM_ERR_FAILED;
1834        }
1835
1836        do
1837        {
1838                /* Check to see if scan was canceled */
1839                if (chm_check_cancel(p_chm))
1840                        break;
1841
1842                ch_map_get_counts(&p_chm->ch_map,&num_vch,&num_st,&num_freq);
1843
1844                /* When in hunt mode only get require CDS then transition into pending init mode */
1845                if (p_chm->cmd == eCHM_HUNTING)
1846                {
1847                        if (SI_NIT_CDS_Complete() && SI_NIT_MMS_Complete())
1848                                done = true;
1849                        else
1850                                done  = (timeout < bapp_task_getticks());
1851                } else
1852                {
1853                        /* In Pending Init mode both CDS and VCH are required to exit. */
1854                        if (p_chm->cds_changed && p_chm->mms_changed && p_chm->vcm_changed && p_chm->sns_changed)
1855                                done = true;
1856                        else
1857                                done  = (timeout < bapp_task_getticks()) && (num_freq > 0) && (num_vch > 0);
1858                }
1859
1860                if (chm_check_cancel(p_chm))
1861                {
1862                        return eCHM_ERR_CANCELED;
1863                }
1864                bapp_task_sleep(CHM_IDLE_TIMEOUT);
1865        }while (!done);
1866
1867        chm_nit_stop(p_chm);
1868        if (p_chm->cmd != eCHM_HUNTING)
1869        {
1870                chm_svct_stop(p_chm);
1871                chm_ntt_stop(p_chm);
1872        }
1873
1874        ch_map_get_counts(&p_chm->ch_map,&num_vch,&num_st,&num_freq);
1875        BDBG_MSG(("%s num_vch = %d,num_st = %d,num_freq = %d \n",__FUNCTION__,num_vch,num_st,num_freq));
1876        return(timeout < bapp_task_getticks()) ? eCHM_ERR_TIMEOUT : num_vch;
1877
1878}
1879
1880/*
1881Summary:
1882process the MMS string and associated tables.
1883Returns non-zero on failure.
1884 */
1885
1886int chm_process_mss(chm_mgr_t *p_chm,                           /* Channel manager reference */
1887                                        PSIP_MSS_string p_mms,                  /* Pointer to MMS */
1888                                        unsigned char* mms_buf,                 /* string buffer */
1889                                        unsigned int mms_len                    /* string buffer length */
1890                                   )
1891{
1892        int str_idx,lsize;
1893        char *p_code;
1894        BERR_Code retcode;
1895        int num_str;
1896        bapp_t *p_app;
1897
1898        if (!p_mms)
1899                return eCHM_ERR_FAILED;
1900
1901        num_str = PSIP_MSS_getNumStrings(p_mms);
1902        p_app = (bapp_t*)p_chm->p_app;
1903        bapp_util_memset(mms_buf,0,mms_len);
1904
1905        for (str_idx = 0; str_idx < num_str; ++str_idx)
1906        {
1907                if ((retcode = PSIP_MSS_getCode(p_mms,str_idx, &p_code)) != BERR_SUCCESS)
1908                {
1909                        BDBG_WRN(("PSIP_MSS_getCode:%d failed %d\n",__LINE__,retcode));
1910                        bapp_util_memset(mms_buf,0,mms_len);
1911                        continue;
1912                }
1913
1914                lsize = mms_len;
1915                if (chm_valid_lang(p_chm,p_code) != (int)p_app->lang)
1916                {
1917#ifdef BDBG_DEBUG_BUILD
1918                        if ((retcode = PSIP_MSS_getString(p_mms,str_idx,&lsize, (char*)mms_buf)) != BERR_SUCCESS)
1919                        {
1920                                BDBG_WRN(("PSIP_MSS_getCode:%d failed %d\n",__LINE__,retcode));
1921                        }
1922
1923                        if (lsize > 0)
1924                        {
1925                                BDBG_MSG(("Lang mismatch %c%c%c %s\n",p_code[0],p_code[1],p_code[2],mms_buf));
1926                        }
1927                        bapp_util_memset(mms_buf,0,mms_len);
1928#endif
1929                        continue;
1930                }
1931
1932
1933                if ((retcode = PSIP_MSS_getString(p_mms,str_idx,&lsize, (char*)mms_buf)) != BERR_SUCCESS)
1934                {
1935                        BDBG_ERR(("MSS invalid %d\n",retcode));
1936                        bapp_util_memset(mms_buf,0,mms_len);
1937                }
1938
1939                BDBG_MSG(("%s:%d idx = %d, %d/%d-%s\n",__FUNCTION__,__LINE__,str_idx,lsize,mms_len,mms_buf));
1940
1941                return 0;
1942        }
1943
1944        /* in case no valid language exists just use first string */
1945        if (num_str > 0)
1946        {
1947                lsize = mms_len;
1948                if ((retcode = PSIP_MSS_getString(p_mms,0,&lsize, (char*)mms_buf)) == BERR_SUCCESS)
1949                {
1950                        BDBG_WRN(("No language match using default\n"));
1951                        return eCHM_ERR_OK;
1952                } else
1953                {
1954                        BDBG_WRN(("PSIP_MSS_getString failed %d\n",retcode));
1955                }
1956
1957        }
1958        BDBG_WRN(("%s:%d no valid string found, num_str = %d\n",__FUNCTION__,__LINE__,num_str));
1959        return eCHM_ERR_FAILED;
1960}
1961
1962/*
1963Summary:
1964Hunt for an SCTE65 Channel on the given frequency.
1965 */
1966
1967static bool chm_hunt_channel(chm_mgr_t *p_chm, 
1968                                                         unsigned int freq_hz, 
1969                                                         unsigned short *network_pid)
1970{
1971        unsigned short num_vch; 
1972        unsigned short num_st;
1973        unsigned char num_freq; 
1974        int num;
1975        bapp_t *p_app = (bapp_t*)p_chm->p_app;
1976        bapp_freq_table_get(p_chm->fe_type,(const unsigned int **)&(p_chm->freq_table),&(p_chm->num_freq));
1977
1978        /* Try tuning */
1979        if (bapp_tune_lock(p_chm->tune,freq_hz) != eBAPP_RESULT_OK)
1980        {
1981                BDBG_WRN(("FREQ[%d] freq = %d not locked, try next freq\n",p_chm->select_idx,freq_hz));
1982                /* Send message to app */
1983                chm_send_status(p_chm,freq_hz,false);
1984                return false;
1985        } 
1986        else
1987        {
1988                BDBG_WRN(("btuner_tune_[%d] freq = %d, success\n",p_chm->select_idx,freq_hz));
1989                chm_send_status(p_chm,freq_hz,true);
1990        }
1991
1992        BDBG_WRN(("chm_scan_cat \n"));
1993        if (chm_scan_cat(p_chm,p_chm->band,freq_hz) != eCHM_ERR_OK)
1994        {
1995                BDBG_WRN(("chm_scan_cat - No valid EMM PID found\n"));
1996#ifdef CONFIG_REQUIRE_CAT
1997                return false;
1998#endif
1999                BDBG_WRN(("chm_scan_cat - using default PID\n"));
2000        }
2001        bapp_util_sleep(500);
2002
2003        if (chm_scan_network(p_chm,p_chm->band,network_pid) != eCHM_ERR_OK)
2004        {
2005                BDBG_WRN(("chm_scan_network - No network PID found, use default\n"));
2006        }
2007
2008        p_chm->chm_network_evt.type = eCHM_EVT_NETWORK;
2009        p_chm->chm_network_evt.id = *network_pid;
2010        chm_post_app_event(p_chm,&p_chm->chm_network_evt);
2011
2012        chm_emm_start( p_chm, p_app->settings.EMM_PID );
2013        chm_stt_start(p_chm,*network_pid);
2014
2015        if ((num = chm_scan_scte65(p_chm,p_chm->band,*network_pid)) <= 0)
2016        {
2017                BDBG_WRN(("chm_scan_scte65 no virtual channels\n"));
2018        } else
2019        {
2020                BDBG_MSG(("chm_scan_scte65 found %d \n", num));
2021        }
2022
2023        chm_stt_stop(p_chm);
2024        chm_emm_stop(p_chm);
2025
2026        ch_map_get_counts(&p_chm->ch_map,&num_vch,&num_st,&num_freq);
2027
2028        return(num_freq > 0);
2029}
2030/*
2031Summary:
2032Process pending initialization state.
2033 */
2034
2035static void chm_pending_init(chm_mgr_t *p_chm           /* Channel manager reference */
2036                                                        )
2037{
2038        unsigned short network_pid,vct_id;
2039        bapp_t *p_app = (bapp_t*)p_chm->p_app;
2040        ch_map_t *p_ch_map = bapp_cur_ch_map(p_app);
2041        unsigned int timeout;
2042
2043        if (p_app->settings.activated && (p_app->settings.timeout_cnt > 0) && (p_ch_map->vch_map.num_vch > 0))
2044        {
2045                p_chm->cmd = eCHM_CANCEL;
2046                p_chm->chmap_evt.type = eCHM_EVT_STATUS;
2047                p_chm->chmap_evt.id = eCHM_STATUS_CHMAP;
2048                BDBG_WRN(("%s - Activated and has a map\n",__FUNCTION__));
2049                p_chm->chmap_evt.ticks = 0;
2050                chm_post_app_event(p_chm,&p_chm->chmap_evt);
2051                return;
2052        }
2053
2054        p_chm->chm_pending_evt.type = eCHM_EVT_STATUS;
2055        p_chm->chm_pending_evt.id = eCHM_STATUS_PENDING_INIT;
2056        chm_post_app_event(p_chm,&p_chm->chm_pending_evt);
2057
2058        if (chm_scan_network(p_chm,p_chm->band,&network_pid) != eCHM_ERR_OK)
2059        {
2060                BDBG_WRN(("chm_scan_network - No network PID found, use default\n"));
2061        }
2062
2063        chm_cvt_start(p_chm,network_pid);
2064        chm_stt_start(p_chm,network_pid);
2065
2066        /* scan for VCH if none exists */
2067        vct_id = p_app->settings.VCT_ID;
2068        if (p_chm->ch_map.vch_map.num_vch == 0)
2069        {
2070                if (chm_svct_start(p_chm,network_pid) != eCHM_ERR_OK)
2071                {
2072                        p_chm->cmd = eCHM_CANCEL;
2073                        return;
2074                }
2075                if (chm_ntt_start(p_chm,network_pid) != eCHM_ERR_OK)
2076                {
2077                        p_chm->cmd = eCHM_CANCEL;
2078                        return;
2079                }
2080        }
2081
2082        chm_emm_start(p_chm,p_app->settings.EMM_PID);
2083
2084        timeout = bapp_task_getticks() + MS_TO_TICKS(SVCT_TIMEOUT);
2085
2086        /* For testing ### REMOVE */
2087#if 1
2088#warning "FOR TEST PURPOSES ONLY:  Activate and set default timeout count to 8"
2089        p_app->settings.activated = 1;
2090        p_app->settings.timeout_cnt = 8;
2091#endif
2092        while ((p_chm->ch_map.vch_map.num_vch == 0) || (timeout > bapp_task_getticks()) || !p_app->settings.activated)
2093        {
2094                if (p_chm->cds_changed && p_chm->mms_changed && p_chm->vcm_changed && p_chm->sns_changed)
2095                {
2096                        BDBG_MSG(("%s - Full channel map received\n",__FUNCTION__));
2097
2098                        /* if we are not expecting a config message and activated, break out of the while loop. */
2099                        if (p_app->settings.activated)
2100                        {
2101                                BDBG_WRN(("Full Channel Map Received and Activated!\n" ));
2102                                bapp_task_sleep(CHM_IDLE_TIMEOUT);
2103                                break;
2104                        }
2105                }
2106
2107                /* Check to see if scan was canceled */
2108                if (chm_check_cancel(p_chm))
2109                {
2110                        /* leave pending state */
2111                        p_chm->cmd = eCHM_CANCEL;
2112                        break;
2113                }
2114
2115                /* Check to see if configuration message was received.  If so restart svct. */
2116                if (vct_id != p_app->settings.VCT_ID)
2117                {
2118                        vct_id = p_app->settings.VCT_ID;
2119                        BDBG_WRN(("configuration message was received while pending, get SVCT with VCTID = 0x%04x!\n",vct_id));
2120                        timeout = bapp_task_getticks() + MS_TO_TICKS(SVCT_TIMEOUT);
2121                        if (chm_svct_start(p_chm,network_pid) != eCHM_ERR_OK)
2122                        {
2123                                p_chm->cmd = eCHM_CANCEL;
2124                                return;
2125                        }
2126                }
2127                bapp_task_sleep(CHM_IDLE_TIMEOUT);
2128        }
2129        if (chm_check_cancel(p_chm))
2130        {
2131                /* leave scan state */
2132                p_chm->cmd = eCHM_CANCEL;
2133                return;
2134        }
2135        chm_cache_pids(p_chm);
2136
2137        p_chm->chmap_evt.ticks = ch_map_cmp(&(p_chm->ch_map),&(p_app->settings.ch_map));
2138        if (p_chm->chmap_evt.ticks)
2139        {
2140                /* copy channel map so application can perform update without risk of modification by channel manager */
2141                p_chm->chmap_evt.type = eCHM_EVT_STATUS;
2142                p_chm->chmap_evt.id = eCHM_STATUS_CHMAP;
2143                BDBG_WRN(("%s - Activated and New Channel Map\n",__FUNCTION__));
2144                chm_post_app_event(p_chm,&p_chm->chmap_evt);
2145                bapp_task_sleep(200);
2146        }
2147        chm_ntt_stop(p_chm);
2148        chm_svct_stop(p_chm);
2149        chm_stt_stop(p_chm);
2150
2151        chm_cvt_stop(p_chm);
2152        chm_emm_stop(p_chm);
2153
2154        if (chm_check_cancel(p_chm))
2155        {
2156                /* leave scan state */
2157                p_chm->cmd = eCHM_CANCEL;
2158                return;
2159        }
2160
2161        /* Force transition into normal mode */
2162        if (!p_chm->chmap_evt.ticks)
2163        {
2164                p_chm->chmap_evt.type = eCHM_EVT_STATUS;
2165                p_chm->chmap_evt.id = eCHM_STATUS_CHMAP;
2166                p_chm->chmap_evt.ticks = 0x0;
2167                BDBG_WRN(("%s - Send empty map event \n",__FUNCTION__));
2168
2169                chm_post_app_event(p_chm,&p_chm->chmap_evt);
2170        }
2171        p_chm->cmd = eCHM_CANCEL;
2172
2173}
2174/*
2175Summary:
2176Hunt for an SCTE65 Channel Map.
2177Description:
2178Scan for all available channels.
2179 */
2180
2181static void chm_hunt(chm_mgr_t *p_chm           /* Channel manager reference */
2182                                        )
2183{
2184        unsigned int freq;
2185        unsigned short network_pid;
2186        bapp_t *p_app = (bapp_t*)p_chm->p_app;
2187
2188        /* reset last frequency to force tune first channel change after getting a new map */
2189        p_chm->last_freq_hz = 0;
2190
2191        p_chm->chm_hunt_evt.type = eCHM_EVT_STATUS;
2192        p_chm->chm_hunt_evt.id = eCHM_STATUS_HUNT;
2193        chm_post_app_event(p_chm,&p_chm->chm_hunt_evt);
2194
2195        chm_stop_decode(p_chm);
2196
2197        /* Completely reset and start over */
2198        ch_map_reset(&(p_chm->ch_map));
2199
2200        /* Add streamer channel */
2201        p_app->settings.psi_scan = 1;
2202        if (p_app->settings.psi_scan)
2203        {
2204                BDBG_WRN(("%s - PSI Scan Channel Map\n",__FUNCTION__));
2205                /* Fallback to simple SI scan */
2206                chm_scan(p_chm);
2207
2208                p_chm->chmap_evt.type = eCHM_EVT_STATUS;
2209                p_chm->chmap_evt.id = eCHM_STATUS_CHMAP;
2210                p_chm->chmap_evt.ticks = 0xF;
2211                /* copy channel map so application can perform update without risk of modification by channel manager */
2212                chm_post_app_event(p_chm,&p_chm->chmap_evt);
2213                BDBG_WRN(("%s - PSI Scan Channel Map\n",__FUNCTION__));
2214                bapp_task_sleep(200);
2215                /* leave scan state */
2216                p_chm->cmd = eCHM_CANCEL;
2217                return;
2218        }
2219
2220        /* Check "turn on QAM" */
2221        if (p_app->settings.turn_on_freq_khz != 0)
2222        {
2223                if (!chm_hunt_channel(p_chm,p_app->settings.turn_on_freq_khz * 1000,&network_pid))
2224                {
2225                        BDBG_WRN(("Turn on QAM tune failed %d KHz.\n",p_app->settings.turn_on_freq_khz));
2226                        p_app->settings.turn_on_freq_khz = 0;
2227                        p_app->settings_dirty = true;
2228                } else
2229                {
2230                        BDBG_WRN(("Turn on QAM tune %d KHz. OK\n",p_app->settings.turn_on_freq_khz));
2231
2232                        /* leave scan state */
2233                        p_chm->cmd = eCHM_PENDING_INIT;
2234                        p_chm->select_idx = p_chm->num_freq;
2235                        return;
2236                }
2237        }
2238
2239        /* check for SCTE-65 data */
2240        for (p_chm->select_idx = 0; p_chm->select_idx <  p_chm->num_freq; p_chm->select_idx++)
2241        {
2242                freq = (unsigned int)p_chm->freq_table[p_chm->select_idx];
2243                freq *= 1000; /* convert to Hz */
2244                BDBG_WRN(("Hunt[%d of %d] freq = %d\n",p_chm->select_idx,p_chm->num_freq,freq));
2245
2246                /* Check to see if scan was canceled */
2247                if (chm_check_cancel(p_chm))
2248                {
2249                        /* leave scan state */
2250                        p_chm->cmd = eCHM_CANCEL;
2251                        return;
2252                }
2253
2254                if (!chm_hunt_channel(p_chm,freq,&network_pid))
2255                {
2256                        BDBG_WRN(("Hunt failed %d Hz.\n",freq));
2257                } else
2258                {
2259                        BDBG_WRN(("Set turn on QAM to %d Hz. OK\n",freq));
2260                        p_app->settings.turn_on_freq_khz = freq/1000;
2261                        p_app->settings_dirty = true;
2262
2263                        /* leave scan state */
2264                        p_chm->cmd = eCHM_PENDING_INIT;
2265                        p_chm->select_idx = p_chm->num_freq;
2266                        break;
2267                }
2268        }
2269        p_chm->hunt_cnt++;
2270}
2271
2272
2273/*
2274Summary:
2275Update the program pids associated with the freq_idx.
2276Assumes that the channel manager channel map semaphore is already acquired.
2277Returns chm error codes.
2278 */
2279
2280static int chm_update_programs(chm_mgr_t *p_chm,                /* Channel manager reference */
2281                                                           int freq_idx                                   /* frequency index */
2282                                                          )
2283{
2284        unsigned int section_size, pmt_section_size;
2285        TS_PMT_stream pmt;
2286        TS_PAT_program pat;
2287        int result = 0;
2288        int idx,p_idx;
2289        vch_t vch;
2290        TS_PSI_descriptor psi_desc,lang_desc;
2291        int strm_idx,vch_idx,desc_idx;
2292        bapp_t *p_app = (bapp_t*)p_chm->p_app;
2293
2294        smessage_stream_params_init(&p_chm->msg_params, p_chm->smsg);
2295        p_chm->msg_params.band = p_chm->band;
2296        p_chm->msg_params.pid = (unsigned short)0;      /* PAT */
2297        section_size = PAT_BUF_LEN;
2298        bapp_util_memset(&vch,0,sizeof(vch));
2299
2300        if ((result = chm_getmessage(p_chm,p_chm->pat_buf,&section_size, PAT_TIMEOUT)) != 0)
2301        {
2302                BDBG_WRN(("%s(%d): Error getting PAT 0x%04x = %d\n",__FUNCTION__,__LINE__,p_chm->vch.program_num, result));
2303                return eCHM_ERR_NO_PAT;
2304        }
2305
2306        if (TS_PAT_validate(p_chm->pat_buf, section_size) != true)
2307        {
2308                BDBG_WRN(("TS_PAT_validate failed\n"));
2309                return eCHM_ERR_NO_PAT;
2310        }
2311
2312
2313        if (TS_PAT_getNumPrograms(p_chm->pat_buf) == 0)
2314        {
2315                BDBG_WRN(("%s TS_PAT_getNumPrograms = 0\n",__FUNCTION__));
2316                DBG_HEXDUMP(p_chm->pat_buf,section_size);
2317                return eCHM_ERR_NO_PAT;
2318        }
2319
2320        BDBG_WRN(("TS_PAT_getNumPrograms %d\n",TS_PAT_getNumPrograms(p_chm->pat_buf)));
2321
2322        for (vch_idx = 0; vch_idx < p_chm->ch_map.vch_map.num_vch; vch_idx++)
2323        {
2324                /* Only process entries which match the current frequency index */
2325                if (p_chm->ch_map.vch_map.vch[vch_idx].freq_idx != freq_idx)
2326                        continue;
2327
2328                /* copy current vch */
2329                vch = p_chm->ch_map.vch_map.vch[vch_idx];
2330
2331                /* Process the PAT to find the correct program to update */
2332                for (idx = 0; idx < TS_PAT_getNumPrograms(p_chm->pat_buf); idx++)
2333                {
2334                        if (TS_PAT_getProgram( p_chm->pat_buf, section_size, idx, &pat ) != b_ok)
2335                        {
2336                                BDBG_WRN(("TS_PAT_getProgram(%d,0x%04x)\n", idx,pat.PID));
2337                                return eCHM_ERR_NO_PAT;
2338                        }
2339
2340                        if (pat.program_number != vch.program_num)
2341                        {
2342                                BDBG_WRN(("pat.program_number != prog_number (%d != %d)\n", pat.program_number, vch.program_num));
2343                                continue;
2344                        }
2345
2346                        smessage_stream_params_init(&p_chm->msg_params, p_chm->smsg);
2347                        p_chm->msg_params.band = p_chm->band;
2348                        p_chm->msg_params.pid = (unsigned short)pat.PID;        /* PMT */
2349                        p_chm->msg_params.filter.coef[0] = 0x2;
2350                        p_chm->msg_params.filter.mask[0] = 0x00;
2351                        p_chm->msg_params.filter.excl[0] = 0xff;
2352                        pmt_section_size = PMT_BUF_LEN;
2353                        if ((result = chm_getmessage(p_chm,p_chm->pmt_buf,&pmt_section_size, PMT_TIMEOUT)) != 0)
2354                        {
2355                                BDBG_ERR(("Error getting PMT 0x%04x, prog %d\n",pat.PID,vch.program_num));
2356                                continue;
2357                        }
2358                        p_chm->pmt_crc = chm_section_crc(p_chm->pmt_buf,pmt_section_size);
2359
2360                        vch.num_audio = 0;
2361                        vch.cur_audio = 0;
2362                        vch.pcr_pid = 0;
2363                        vch.video_pid = 0;
2364                        vch.scte127_pid = 0;
2365                        bapp_util_memset(vch.audio_pid,0,sizeof(unsigned short) * MAX_AUDIO_PIDS);
2366                        bapp_util_memset(vch.audio_type,0,sizeof(unsigned char) * MAX_AUDIO_PIDS);
2367                        bapp_util_memset(vch.audio_lang,'_',sizeof(char) * MAX_AUDIO_PIDS * 3);
2368
2369                        vch.pcr_pid = TS_PMT_getPcrPid(p_chm->pmt_buf,pmt_section_size);
2370
2371                        /* Get CA pid */
2372                        desc_idx = 0;
2373                        vch.ca_pid = 0;
2374                        while ((psi_desc = TS_PMT_getDescriptor(p_chm->pmt_buf, pmt_section_size,desc_idx++)) != NULL)
2375                        {
2376                                ca_descriptor ca_desc;
2377
2378                                if (desc_idx > 0xFF)
2379                                {
2380                                        BDBG_ERR(("PMT Desc limit exceeded %d\n",desc_idx));
2381                                        break;
2382                                }
2383                                if (chm_check_cancel(p_chm))
2384                                {
2385                                        return eCHM_ERR_CANCELED;
2386                                }
2387
2388                                if (psi_desc[0] != 9)
2389                                        continue;
2390
2391                                if (ca_parser(psi_desc, pmt_section_size, &ca_desc) == 0)
2392                                        continue;
2393
2394                                if (ca_desc.CA_system_ID == p_app->settings.CA_System_ID)
2395                                {
2396                                        vch.ca_pid = ca_desc.CA_PID;
2397                                        BDBG_WRN(("CA PID = 0x%04x\n",vch.ca_pid));
2398                                        p_app->settings.SCP_operating_mode = 0;
2399                                        if (ca_desc.CA_system_ID == 0x0E11)
2400                                        {
2401                                                /* Send message to app */
2402                                                if ((ca_desc.priv_data[0] == 0x5) && (ca_desc.priv_data[1] == 0x1))
2403                                                        p_app->settings.SCP_operating_mode = ca_desc.priv_data[2];
2404                                        }
2405                                        break;
2406                                }
2407                                else
2408                                {
2409                                        p_chm->system_id_errors++;
2410                                }
2411                        }
2412
2413                        for (p_idx = 0; p_idx < TS_PMT_getNumStreams(p_chm->pmt_buf,pmt_section_size); p_idx++)
2414                        {
2415                                bapp_av_stream_type_t *stream_type;
2416
2417                                if (TS_PMT_getStream( p_chm->pmt_buf, pmt_section_size, p_idx, &pmt ) != b_ok)
2418                                {
2419                                        BDBG_WRN(("Failure processing PMT %d\n",p_idx));
2420                                        break;
2421                                }
2422
2423                                strm_idx = 0;
2424                                lang_desc = NULL;
2425                                /* default is not supported */
2426                                while ((psi_desc = TS_PMT_getStreamDescriptor(p_chm->pmt_buf,pmt_section_size, p_idx,strm_idx)) != NULL)
2427                                {
2428                                        if (psi_desc[0] == TS_PSI_DT_ISO_639_Language) /* 0x0A ISO-639 Language descriptor */
2429                                        {
2430                                                BDBG_WRN(("ISO-639 DESC\n" ));
2431                                                lang_desc = psi_desc;
2432                                                /* if get VBI desc alrady */
2433                                                if (vch.scte127_pid)
2434                                                        break;
2435                                        }
2436                                        if (0 == vch.scte127_pid)
2437                                        {
2438                                                if (TS_PSI_DT_DVB_VBI_Data == psi_desc[0])
2439                                                {
2440                                                        BDBG_WRN(("SCTE 127 supported, pid=0x%04x", pmt.elementary_PID));
2441                                                        vch.scte127_pid = pmt.elementary_PID;
2442                                                        /* if get lang desc alrady */
2443                                                        if (lang_desc)
2444                                                                break;
2445                                                }
2446                                        }
2447                                        strm_idx++;
2448                                        if (strm_idx > 0xFF)
2449                                        {
2450                                                BDBG_ERR(("PMT Stream Desc limit exceeded %d\n",strm_idx));
2451                                                break;
2452                                        }
2453                                        if (chm_check_cancel(p_chm))
2454                                        {
2455                                                return eCHM_ERR_CANCELED;
2456                                        }
2457                                }
2458
2459                                if ((stream_type = bapp_av_supported_video(pmt.stream_type)) != NULL)
2460                                {
2461                                        BDBG_WRN(("Video PID[%d] = 0x%04x\n",p_idx,pmt.elementary_PID ));
2462                                        if (!vch.video_pid)
2463                                        {
2464                                                vch.video_pid = pmt.elementary_PID;
2465                                                vch.video_type = stream_type->codec_id;
2466                                        }
2467                                }
2468                                else if ((stream_type = bapp_av_supported_audio(pmt.stream_type)) != NULL)
2469                                {
2470                                        BDBG_WRN(("Audio PID[%d] = 0x%04x\n",vch.num_audio,pmt.elementary_PID ));
2471                                        if (!vch.audio_pid[vch.num_audio])
2472                                        {
2473                                                vch.audio_pid[vch.num_audio] = pmt.elementary_PID;
2474                                                vch.audio_type[vch.num_audio] = stream_type->codec_id;
2475                                                if (lang_desc)
2476                                                {
2477                                                        vch.audio_lang[vch.num_audio][0] = toupper(lang_desc[2]);
2478                                                        vch.audio_lang[vch.num_audio][1] = toupper(lang_desc[3]);
2479                                                        vch.audio_lang[vch.num_audio][2] = toupper(lang_desc[4]);
2480                                                }
2481                                                BDBG_WRN(("Audio PID[%d][%c%c%c] = 0x%04x, type=0x%04x\n",p_idx,vch.audio_lang[vch.num_audio][0],
2482                                                                  vch.audio_lang[vch.num_audio][1],vch.audio_lang[vch.num_audio][2],pmt.elementary_PID, pmt.stream_type));
2483                                                vch.num_audio++;
2484                                        }
2485                                }
2486                                else
2487                                {
2488                                        BDBG_WRN(("Unsupported stream type[0x%02x]\n", pmt.stream_type));
2489                                }
2490                        } /* for (p_idx = 0; p_idx < TS_PMT_getNumStreams(p_chm->pmt_buf,pmt_section_size); p_idx++) */
2491                        p_chm->ch_map.vch_map.vch[vch_idx] = vch;
2492                        break;
2493                } /* for (idx = 0; idx < TS_PAT_getNumPrograms(p_chm->pat_buf); idx++) */
2494        } /* for (vch_idx = 0; vch_idx < p_chm->ch_map.vch_map.num_vch; vch_idx++) */
2495
2496        return result;
2497}
2498
2499/*
2500Summary:
2501Hunt for an SCTE65 Channel Map.
2502Description:
2503Scan for all available channels.
2504 */
2505
2506static void chm_cache_pids(chm_mgr_t *p_chm             /* Channel manager reference */
2507                                                  )
2508{
2509        int freq_idx,vch_idx,result;
2510        unsigned int freq;
2511        bool found;
2512        bapp_t *p_app = (bapp_t*)p_chm->p_app;
2513
2514        if (bapp_task_acquire_mutex(p_chm->ch_map_mutex,45) != b_ok)
2515        {
2516                BDBG_WRN(("%s:%d failed to acquire channel map mutex\n", __FUNCTION__,__LINE__));
2517                return;
2518        }
2519
2520        for (freq_idx = 0; freq_idx < p_chm->ch_map.freq_map.num_freq; ++freq_idx)
2521        {
2522                found = false;
2523                for (vch_idx = 0; vch_idx < p_chm->ch_map.vch_map.num_vch; vch_idx++)
2524                {
2525                        if (p_chm->ch_map.vch_map.vch[vch_idx].freq_idx == p_chm->ch_map.freq_map.freq[freq_idx].idx)
2526                        {
2527                                found = true;
2528                                break;
2529                        }
2530                }
2531                if (!found)
2532                        continue;
2533
2534
2535                freq = (unsigned int)(p_chm->ch_map.freq_map.freq[freq_idx].freq_khz);
2536                freq *= 1000; /* convert to Hz */
2537                BDBG_WRN(("%s cache[%d] freq = %d\n",__FUNCTION__,freq_idx,freq));
2538
2539                /* Check to see if scan was canceled */
2540                if (chm_check_cancel(p_chm))
2541                        break;
2542
2543                        /* Try tuning */
2544                if (bapp_tune_lock(p_chm->tune,freq) != eBAPP_RESULT_OK)
2545                {
2546                        BDBG_WRN(("FREQ[%d] freq = %d not locked, try next freq\n",freq_idx,freq));
2547                        chm_send_status(p_chm,freq,false);
2548                        continue;
2549                } else
2550                {
2551                        BDBG_WRN(("btuner_tune_xxx[%d] freq = %d, success\n",freq_idx,freq));
2552                        chm_send_status(p_chm,freq,true);
2553                }
2554
2555                if ((result = chm_update_programs(p_chm,p_chm->ch_map.freq_map.freq[freq_idx].idx)) != eCHM_ERR_OK)
2556                {
2557                        BDBG_WRN(("chm_update_programs failed %d\n",result));
2558                        if (result == eCHM_ERR_TIMEOUT)
2559                                break;
2560                        else
2561                                continue;
2562                }
2563        }
2564        /* Go back to turn on QAM in case the map has channels that don't exist */
2565        freq = (unsigned int)p_app->settings.turn_on_freq_khz * 1000; /* Freq in HZ !!! */
2566        BDBG_WRN(("%s Go to turn on QAM freq %dKHz\n",__FUNCTION__,freq));
2567
2568        /* Try tuning */
2569        if (bapp_tune_lock(p_chm->tune,freq) != eBAPP_RESULT_OK)
2570        {
2571                BDBG_WRN(("Turn on freq = %dHz not locked, try next freq\n",freq));
2572                chm_send_status(p_chm,freq,false);
2573        } else
2574        {
2575                BDBG_WRN(("Turn on freq = %dHz, success\n",freq));
2576                chm_send_status(p_chm,freq,true);
2577        }
2578        bapp_task_release_mutex(p_chm->ch_map_mutex);
2579
2580}
2581
2582/*
2583Summary:
2584Post an event the app queue to provide status.
2585 */
2586
2587static int chm_post_app_event_cb(chm_mgr_t *p_chm,              /* Channel manager reference */
2588                                                                 chm_event_t *p_event    /* Event to post to app queue */
2589                                                                )
2590{
2591        bapp_t *p_app = (bapp_t*)p_chm->p_app;
2592        bapp_task_post_event(p_app->msg_queue,(bapp_task_event_t)p_event);
2593
2594        return 0;
2595}
2596
2597/*
2598Summary:
2599Post an event the app queue to provide status.
2600 */
2601
2602static int chm_post_app_event(chm_mgr_t *p_chm,         /* Channel manager reference */
2603                                                          chm_event_t *p_event    /* Event to post to app queue */
2604                                                         )
2605{
2606        int result = chm_post_app_event_cb(p_chm,p_event);
2607
2608        bapp_task_sleep(10);
2609        return result;
2610}
2611
2612#ifdef  HAS_VBI
2613/******************************************************************************
2614 * INPUTS:      context
2615 * OUTPUTS:     none.
2616 * RETURNS:     none
2617 * FUNCTION:    chm_scte_feed_callback
2618 * DESCRIPTION: feed scte 127 data for encoding
2619 ******************************************************************************/
2620static pscte_127_handle s_pscte_127 = NULL;
2621
2622void chm_scte_feed_callback(int field)
2623{
2624        if (s_pscte_127 && scte_127_has_data(s_pscte_127, field))
2625        {
2626                scte_127_feed_data_buf(s_pscte_127, field);
2627        }
2628}
2629
2630/******************************************************************************
2631 * INPUTS:      context
2632 * OUTPUTS:     none.
2633 * RETURNS:     none
2634 * FUNCTION:    message_callback
2635 * DESCRIPTION: Callback function normally called when a complete message has
2636 *              been received and passed the filter criteria.
2637 ******************************************************************************/
2638void * chm_smessage_scte127_callback(void * context, size_t size)
2639{
2640        chm_mgr_t * p_chm = (chm_mgr_t*)context;
2641        bapp_t *p_app;
2642        uint8_t *ptr, *ptr1;
2643        int len;
2644
2645        p_app = (bapp_t*)p_chm->p_app;
2646        //BDBG_MSG(("#### SCTE127 Event (size=%d)####\n", size));
2647
2648        ptr = ptr1 = p_chm->scte127_buf;
2649        if (size != p_chm->scte127_buf_size)
2650        {
2651                if (size % 188)
2652                {
2653                        BDBG_WRN(("Size not match, make adjustment if not multiple of 188"));
2654                        size = (size / 188) * 188;
2655                }
2656        }
2657        for (; size; size -= 188)
2658        {
2659                ptr = pes_parser(ptr, &len);
2660                if (ptr)
2661                {
2662                        /* should be data unit id byte */
2663                        len = (188 - len);
2664                        scte_127_pes_data_field_parser(p_chm->pscte_127, ptr, len);
2665                } else
2666                {
2667                        /* if not private data */
2668                        if (0xff == len)
2669                                break;
2670
2671                        BDBG_WRN(("Invalid SCTE127 packet"));
2672                }
2673                ptr1 += 188;
2674                ptr = ptr1;
2675        }
2676        return(void*)p_chm->scte127_buf;
2677}
2678#endif
2679
2680/******************************************************************************
2681 * INPUTS:      context
2682 * OUTPUTS:     none.
2683 * RETURNS:     none
2684 * FUNCTION:    message_callback
2685 * DESCRIPTION: Callback function normally called when a complete message has
2686 *              been received and passed the filter criteria.
2687 ******************************************************************************/
2688void * chm_smessage_eas_callback(void * context, size_t size)
2689{
2690        TS_SCTE_18_header header;               /* header structure */
2691        chm_mgr_t * p_chm = (chm_mgr_t*)context;
2692        bapp_t *p_app;
2693        unsigned int timegpssec, event_end_time;
2694        unsigned short source_id,exp_source_id;
2695        struct timeval cur;
2696        bool found_sourceid = false;
2697        size_t ex_size,i;
2698        uint8_t *pOffset;
2699
2700        p_app = (bapp_t*)p_chm->p_app;
2701        BDBG_WRN(("#### EAS Event ####\n"));
2702        p_chm->eas_cnt++;
2703
2704        if (!p_app->power)
2705        {
2706                BDBG_WRN(("####EAS Event: DTA in standby state: ignore. #### \n"));
2707                goto ExitFunc;
2708        }
2709
2710        if (TS_SCTE_18_getSectionHeader(p_chm->eas_buf, size, &header) != 0)
2711        {
2712                BDBG_ERR(("#### TS_SCTE_18_getSectionHeader failed ####\n"));
2713                goto ExitFunc;
2714        }
2715
2716        /* for priority == 0, initialize sequence number only per DTA30-DIG-I01-081210 */
2717        if (0 == header.alert_priority)
2718        {
2719                /* establish a new sequence number */
2720                p_chm->sequence_number = header.sequence_number;
2721                goto ExitFunc;
2722        }
2723
2724        if (p_chm->sequence_number == header.sequence_number)
2725        {
2726                BDBG_ERR(("#### EAS Event %d duplicate ####\n",header.sequence_number));
2727                goto ExitFunc;
2728        }
2729        p_chm->sequence_number = header.sequence_number;
2730
2731        if ((int8_t)header.alert_priority < SCTE_18_ALERT_PRIORITY)
2732        {
2733                BDBG_WRN(("#### EAS Event alert priority %d < %d, ignore.#### \n", header.alert_priority, SCTE_18_ALERT_PRIORITY));
2734                goto ExitFunc;
2735        }
2736
2737        if ((int8_t)header.alert_message_time_remaining < 0 || header.alert_message_time_remaining > 120)
2738        {
2739                BDBG_WRN(("#### EAS Event alert_message_time_remaining %d out of range ####\n",header.alert_message_time_remaining));
2740                goto ExitFunc;
2741        }
2742        if (p_chm->EAS_event_ID == header.EAS_event_ID)
2743        {
2744                /* same EAS message, but only time remaining changed */
2745                GETTIMEOFDAY(&cur);
2746                if (header.alert_message_time_remaining)
2747                        p_app->eas_timeout = cur.tv_sec + header.alert_message_time_remaining;
2748                else
2749                        p_app->eas_timeout = 0;
2750
2751                BDBG_MSG(("#### EAS Event %d already processed ####\n",header.EAS_event_ID));
2752                goto ExitFunc;
2753        }
2754        /* new EAS message is distributed */
2755        p_chm->EAS_event_ID = header.EAS_event_ID;
2756
2757        if (header.event_start_time && header.event_duration)
2758        {
2759                /* 15 mins to 100 hours */
2760                if (header.event_duration < 15 || header.event_duration > 600)
2761                {
2762                        BDBG_WRN(("#### EAS Event event_duration %d out of range ####\n",header.event_duration));
2763                        goto ExitFunc;
2764                }
2765                GETTIMEOFDAY(&cur);
2766                timegpssec = p_app->system_time + cur.tv_sec;
2767                event_end_time = header.event_start_time+(header.event_duration * 60);
2768
2769                if (event_end_time < timegpssec)
2770                {
2771                        BDBG_WRN(("#### EAS Event has expired %d < %d, ignore.#### \n", event_end_time, timegpssec));
2772                        goto ExitFunc;
2773                }
2774        }
2775
2776        /* if exception list existed, check to see if current channel is in exception list */
2777        if (header.exception_count)
2778        {
2779                BDBG_WRN(("#### EAS exception count = %d\n",header.exception_count));
2780                pOffset = TS_SCTE_18_getExpectionOffset((const char *)p_chm->eas_buf, &ex_size);
2781                if (pOffset)
2782                {
2783                        vch_t vch;
2784                        st_t st;
2785                        freq_t freq;
2786                        TS_SCTE_18_exception s;
2787
2788                        if (!ch_map_get_current(bapp_cur_ch_map(p_app),&vch,&st,&freq))
2789                        {
2790                                BDBG_WRN(("#### EAS Current channel map invalid.#### \n"));
2791                                goto ExitFunc;
2792                        }
2793                        for (i = 0; i < header.exception_count; i++)
2794                        {
2795                                if (TS_SCTE_18_getException(pOffset, i, &s))
2796                                {
2797                                        BDBG_WRN(("#### EAS exception (%d,0x%04x,0x%04x)\n",s.in_band_reference,s.major_channel_number,s.minor_channel_number));
2798                                        if (s.in_band_reference && ch_map_find_soure_id(bapp_cur_ch_map(p_app),
2799                                                                                                                                        (unsigned char)s.major_channel_number,
2800                                                                                                                                        (unsigned short)s.minor_channel_number,&exp_source_id))
2801                                        {
2802                                                if (exp_source_id == vch.source_id)
2803                                                {
2804                                                        BDBG_WRN(("#### 0x%04x in exception list, discard\n",exp_source_id));
2805                                                        goto ExitFunc;
2806                                                }
2807                                        } else
2808                                        {
2809                                                if (s.OOB_source_ID == vch.source_id)
2810                                                {
2811                                                        BDBG_WRN(("#### OOB 0x%04x in exception list, discard\n",exp_source_id));
2812                                                        goto ExitFunc;
2813                                                }
2814                                        }
2815                                } else
2816                                {
2817                                        BDBG_WRN(("#### EAS TS_SCTE_18_getException %d failed\n",i));
2818                                        goto ExitFunc;
2819                                }
2820                        }
2821                }
2822        }
2823
2824        /* try details OOB source ID first */
2825        if (header.details_OOB_source_ID)
2826        {
2827                BDBG_WRN(("#### EAS Attempt to set details source ID = 0x%04x.#### \n", header.details_OOB_source_ID));
2828                source_id = header.details_OOB_source_ID;
2829                found_sourceid = ch_map_set(bapp_cur_ch_map(p_app),source_id);
2830        }
2831        /* if OOB source ID or not in the VCM */
2832        if (!found_sourceid && (header.details_major_channel_number && header.details_minor_channel_number))
2833        {
2834                BDBG_WRN(("#### EAS Attempt to set major.minor [0x%04x.0x%04x] #### \n", header.details_major_channel_number, header.details_minor_channel_number));
2835                if (!ch_map_find_soure_id(bapp_cur_ch_map(p_app),
2836                                                                  (unsigned char)header.details_major_channel_number,
2837                                                                  (unsigned short)header.details_minor_channel_number,
2838                                                                  &source_id))
2839                {
2840                        /* try audio only */
2841                        if (15 == header.alert_priority && header.audio_OOB_source_ID)
2842                        {
2843                                BDBG_WRN(("#### EAS Attempt to set audio source ID = 0x%04x.#### \n", header.audio_OOB_source_ID));
2844                                source_id = header.audio_OOB_source_ID;
2845                                found_sourceid = ch_map_set(bapp_cur_ch_map(p_app),source_id);
2846                        } else
2847                        {
2848                                BDBG_WRN(("#### EAS no details source ID available\n"));
2849                                goto ExitFunc;
2850                        }
2851                } else
2852                        found_sourceid = true;
2853        }
2854
2855        /* Check for Channel Descriptor */
2856        if (!found_sourceid)
2857        {
2858                /* try channel description */
2859                TS_SCTE_18_in_band_channel_descritpor ib_channel_desc;
2860                pOffset = TS_SCTE_18_getDescriptorOffset((const char *)p_chm->eas_buf, &ex_size);
2861
2862                if (pOffset == NULL)
2863                {
2864                        BDBG_WRN(("#### EAS Channel Descriptor not found #### \n"));
2865                        goto ExitFunc;
2866                }
2867
2868                if (!TS_SCTE_18_getInBandChannelDescriptor(pOffset, &ib_channel_desc,ex_size))
2869                {
2870                        BDBG_WRN(("#### EAS Channel Desc not found #### \n"));
2871                        goto ExitFunc;
2872                }
2873                if (!ch_map_find_soure_id(bapp_cur_ch_map(p_app),
2874                                                                  (unsigned char)ib_channel_desc.exception_RF_channel,
2875                                                                  (unsigned short)ib_channel_desc.exception_program_number,
2876                                                                  &source_id))
2877                {
2878                        BDBG_WRN(("#### EAS sourceID not found for ib channel desc [0x%04x.0x%04x] #### \n", ib_channel_desc.exception_RF_channel, ib_channel_desc.exception_program_number));
2879                        goto ExitFunc;
2880                }
2881        }
2882
2883        if ( ((header.location_code_count) < 1) || ((header.location_code_count) > 31) )
2884        {
2885                BDBG_WRN(("#### EAS location code count invalid %d #### \n",header.location_code_count));
2886                goto ExitFunc;
2887        } else
2888        {
2889                pOffset = TS_SCTE_18_getLocationOffset((const char *)p_chm->eas_buf, &size);
2890                if (pOffset)
2891                {
2892                        TS_SCTE_18_location_code s;
2893                        for (i = 0; i < header.location_code_count; i++)
2894                        {
2895                                if (TS_SCTE_18_getLocationCode(pOffset, i, &s))
2896                                {
2897                                        if ( (((int8_t)s.state_code) < 0) || ((s.state_code) > 99) || 
2898                                                 (((int8_t)s.county_subdivision) < 0) || ((s.county_subdivision) > 9) ||
2899                                                 (((int8_t)s.county_code) < 0) || ((s.county_code) > 999) )
2900                                        {
2901                                                BDBG_WRN(("#### EAS state code %d or subdivision %d country_code %d invalid#### \n",s.state_code, s.county_subdivision, s.county_code));
2902                                                goto ExitFunc;
2903                                        }
2904                                } else
2905                                {
2906                                        goto ExitFunc;
2907                                }
2908                        }
2909                } else
2910                {
2911                        goto ExitFunc;
2912                }
2913        }
2914
2915        if (ch_map_set(bapp_cur_ch_map(p_app),source_id))
2916        {
2917                BDBG_WRN(("#### EAS source ID = 0x%04x found (timeout %d secs).#### \n", source_id,header.alert_message_time_remaining));
2918                p_chm->chm_eas_evt.type = eCHM_EVT_EAS;
2919                p_chm->chm_eas_evt.id = (header.alert_message_time_remaining << 16) | source_id;
2920                p_chm->eas_timer_started = true;
2921                chm_post_app_event_cb(p_chm,&p_chm->chm_eas_evt);
2922        } else
2923        {
2924                BDBG_ERR(("#### EAS source ID = 0x%04x not found.#### \n", source_id));
2925        }
2926        ExitFunc:
2927        return(void*)p_chm->eas_buf;
2928}
2929/******************************************************************************
2930* INPUTS:      context
2931* OUTPUTS:     none.
2932* RETURNS:     none
2933* FUNCTION:    message_callback
2934* DESCRIPTION: Callback function normally called when a complete message has
2935*              been received and passed the filter criteria.
2936******************************************************************************/
2937#if defined(ENABLE_UMESSAGE)
2938static struct udta_message umessage;
2939static struct udta_subcommand  usubcommand;
2940static struct udta_network_config unetwork_config;
2941static struct udta_descriptor udescriptor;
2942static struct udta_time_zone_descriptor utime_zone_descriptor;
2943static struct udta_eas_location_descriptor ueas_descriptor;
2944static struct udta_site_announcement_subcommand usite;
2945static struct udta_phone_number_descriptor uphone_descriptor;
2946static struct udta_reset_user_processor_subcommand ureset;
2947static struct udta_key_table_subcommand keyt;
2948static struct udta_eas_filter_control_subcommand efc;
2949static struct udta_content_control ccm;
2950static struct udta_scp_amm amm;
2951static struct udta_scp_acm acm;
2952static struct udta_encrypted_global_key egk;
2953static struct udta_soc_type soc_type;
2954
2955void* chm_smessage_emm_callback(void * context, size_t size)
2956{
2957        chm_mgr_t * p_chm = (chm_mgr_t*)context;
2958        unsigned char hw_address[6];
2959        unsigned char singlecast_address[6];
2960        struct udta_subcommand_count cnt;
2961        struct udta_parser_state pst;
2962        uint16_t parsed_len;
2963        int subcmd_count, idx;
2964        bapp_t *p_app;
2965
2966        p_chm->emm_count++;
2967        BDBG_MSG(("#### %s #### \n", __FUNCTION__));
2968
2969        p_app = (bapp_t*)p_chm->p_app;
2970
2971        if (!get_hw_address(hw_address))
2972                return(void*)(p_chm->emm_buf);
2973
2974        bapp_util_memset(&umessage,0,sizeof(umessage));
2975        udta_parser_start(p_chm->emm_buf, &pst);
2976        udta_parse_message(&pst, &umessage);
2977
2978        if (umessage.address_type == 1)
2979        {
2980                unsigned int utc_time;
2981                singlecast_address[0] = umessage.singlecast_address[4];
2982                singlecast_address[1] = umessage.singlecast_address[3];
2983                singlecast_address[2] = umessage.singlecast_address[2];
2984                singlecast_address[3] = umessage.singlecast_address[1];
2985                singlecast_address[4] = umessage.singlecast_address[0];
2986                if (memcmp(singlecast_address,hw_address,5) == 0)
2987                {
2988                        /* valid singlecast message */
2989                        get_utc_time(p_app,&utc_time);
2990                        p_app->settings.addressable_time = utc_time;
2991                } else
2992                {
2993                        return(void*)(p_chm->emm_buf);
2994                }
2995
2996        } else if (umessage.address_type == 0)
2997        {
2998                BDBG_WRN(("Broadcast message:  %d\n",umessage.message_type));
2999        } else {
3000                goto ExitFunc;
3001        }
3002
3003        BDBG_WRN(("EMM message type 0x%02X\n", umessage.message_type));
3004
3005        switch (umessage.message_type)
3006        {
3007        case UDTA_CONTENT_CONTROL:
3008                p_chm->ccm_cnt++;
3009                udta_parse_content_control(&pst, &ccm);
3010                for (idx = 0; idx < ccm.soc_type_count; ++idx)
3011                {
3012                        udta_parse_soc_type(&pst, &soc_type);
3013                        /* TODO put into soc type structure */
3014                }
3015                /* TODO Send to application for storage */
3016                break;
3017        case UDTA_SCP_AMM:
3018                p_chm->amm_cnt++;
3019                udta_parse_scp_amm(&pst, &amm);
3020                /* TODO Send to application for storage */
3021                break;
3022        case UDTA_SCP_ACM_EVEN:
3023                p_chm->acm_even_cnt++;
3024                udta_parse_scp_acm(&pst, &acm);
3025                cmode_acm_handler(0x80, &acm, 0);
3026                break;
3027        case UDTA_SCP_ACM_ODD:
3028                p_chm->acm_odd_cnt++;
3029                udta_parse_scp_acm(&pst, &acm);
3030                cmode_acm_handler(0x80, &acm, 1);
3031                break;
3032        case UDTA_CONFIGURATION_1:
3033        case UDTA_CONFIGURATION_2:
3034                p_chm->cfg_cnt++;
3035                udta_parse_subcommand_count(&pst, &cnt);
3036                subcmd_count = cnt.subcommand_count;
3037                while (subcmd_count--)
3038                {
3039                        udta_parse_subcommand(&pst,&usubcommand);
3040                        BDBG_WRN(("DCT CONFIG Subcommand %d\n",usubcommand.subcommand_id));
3041
3042                        switch (usubcommand.subcommand_id)
3043                        {
3044                        case UDTA_NETWORK_CONFIG:
3045                                udta_parse_network_config(&pst, &unetwork_config);
3046
3047                                if (p_chm->cmd == eCHM_PENDING_INIT)
3048                                {
3049                                        /* since we are alread in pending init mode there is no need to notify application of VCT_ID change. */
3050                                        if (p_app->settings.VCT_ID != unetwork_config.home_vct_id)
3051                                        {
3052                                                BDBG_WRN(("%s:%d Configuration VCT_ID %d does not match current value %d\n",
3053                                                                  __FUNCTION__,__LINE__,unetwork_config.home_vct_id, p_app->settings.VCT_ID));
3054                                                p_chm->ch_map.vch_map.num_vch = 0;
3055                                                p_app->settings.VCT_ID = unetwork_config.home_vct_id;
3056                                                p_app->settings.activated = false;
3057                                        }
3058                                } else
3059                                {
3060                                        p_chm->vct_id_evt.type = eCHM_EVT_VCT_ID;
3061                                        p_chm->vct_id_evt.id = unetwork_config.home_vct_id;
3062                                        chm_post_app_event(p_chm,&p_chm->vct_id_evt);
3063                                }
3064                                BDBG_WRN(("chm_smessage_emm_callback()- DCT Network Configuration Message Received! VctId: %d \n", unetwork_config.home_vct_id ));
3065
3066                                if (p_chm->cmd == eCHM_PENDING_INIT)
3067                                {
3068                                        /* since we are alread in pending init mode there is no need to notify application of VCT_ID change. */
3069                                        p_app->settings.timeout = unetwork_config.site_timeout;
3070                                        p_app->settings.timeout_cnt = unetwork_config.site_timeout;
3071                                        p_app->settings.location = unetwork_config.site_code;
3072                                        p_app->settings.timeout_policy  = unetwork_config.timeout_policy;
3073                                        p_app->settings.max_location_errors = unetwork_config.max_site_errors;
3074
3075                                        if (p_app->settings.VCT_ID != unetwork_config.home_vct_id)
3076                                        {
3077                                                BDBG_WRN(("%s:%d Configuration VCT_ID %d does not match current value %d\n",
3078                                                                  __FUNCTION__,__LINE__,unetwork_config.home_vct_id,p_app->settings.VCT_ID));
3079                                                p_chm->ch_map.vch_map.num_vch = 0;
3080                                                p_app->settings.VCT_ID = unetwork_config.home_vct_id;
3081                                                p_app->settings.activated = false;
3082                                        }
3083                                }
3084                                p_chm->config_evt.type = eCHM_EVT_CONFIGURATION;
3085                                p_chm->config_evt.location = unetwork_config.site_code;
3086                                p_chm->config_evt.timeout = unetwork_config.site_timeout;
3087                                p_chm->config_evt.timeout_policy = unetwork_config.timeout_policy;
3088                                p_chm->config_evt.max_location_errors = unetwork_config.max_site_errors;
3089
3090                                if (p_chm->config_evt.VCT_ID != unetwork_config.home_vct_id)
3091                                {
3092                                        p_chm->refresh_count++;
3093
3094                                        BDBG_WRN(("Changing VCT-ID from 0x%04X to 0x%04X; count = %d\n",
3095                                                          p_chm->config_evt.VCT_ID, unetwork_config.home_vct_id, p_chm->refresh_count));
3096                                }
3097                                p_chm->config_evt.VCT_ID = unetwork_config.home_vct_id;
3098                                chm_post_app_event(p_chm,(chm_event_t*)&p_chm->config_evt);
3099
3100                                parsed_len = pst.bits.bindex >> 3;
3101                                /* if we have more message body parse descriptors */
3102                                while(parsed_len < umessage.message_length){
3103                                        udta_parse_descriptor(&pst, &udescriptor);
3104                                        switch(udescriptor.descriptor_tag){
3105                                        case UDTA_TIME_ZONE_DESCRIPTOR:
3106                                                udta_parse_timezone_descriptor(&pst, &utime_zone_descriptor);
3107                                                p_chm->tz_evt.type = eCHM_EVT_TIMEZONE;
3108                                                p_chm->tz_evt.dst_delta = utime_zone_descriptor.daylight_savings_delta_time;
3109                                                p_chm->tz_evt.dst_entry = utime_zone_descriptor.daylight_savings_entry_time;
3110                                                p_chm->tz_evt.dst_exit = utime_zone_descriptor.daylight_savings_exit_time;
3111                                                p_chm->tz_evt.utc_offset = utime_zone_descriptor.time_zone_offset;
3112                                                chm_post_app_event(p_chm,(chm_event_t*)&p_chm->tz_evt);
3113
3114                                                break;
3115                                        case UDTA_EAS_LOCATION_DESCRIPTOR:
3116                                                udta_parse_eas_location_descriptor(&pst, &ueas_descriptor);
3117                                                break;
3118                                        default:
3119                                                udta_skip_descriptor(&pst, &udescriptor);
3120                                                break;
3121                                        }
3122                                        parsed_len = pst.bits.bindex >> 3;
3123                                }
3124                                break;
3125                        default:
3126                                udta_skip_subcommand(&pst, &usubcommand);
3127                                break;
3128                        }
3129                }
3130                break;
3131
3132        case UDTA_OPERATIONS_1:
3133        case UDTA_OPERATIONS_2:
3134                p_chm->ops_cnt++;
3135                udta_parse_subcommand_count(&pst, &cnt);
3136                subcmd_count = cnt.subcommand_count;
3137                while (subcmd_count--)
3138                {
3139                        udta_parse_subcommand(&pst, &usubcommand);
3140                        BDBG_WRN(("DCT OPP Subcommand %d\n",usubcommand.subcommand_id));
3141                        switch (usubcommand.subcommand_id)
3142                        {
3143                        case UDTA_INITIALIZE:
3144                                BDBG_WRN(("chm_smessage_emm_callback() DCT_INITIALIZE_SCMD \n" ));
3145
3146                                p_chm->reset_evt.type = eCHM_EVT_RESET;
3147                                p_chm->reset_evt.id = 4;
3148                                chm_post_app_event(p_chm,&p_chm->reset_evt);
3149                                break;
3150                        case UDTA_RESET_USER_PROCESSOR:
3151                                BDBG_WRN(("chm_smessage_emm_callback() DCT_RESET_USER_PROCESSOR_SCMD \n" ));
3152                                udta_parse_reset_user_processor_subcommand(&pst, &ureset);
3153                                p_chm->reset_evt.type = eCHM_EVT_RESET;
3154                                p_chm->reset_evt.id = ureset.reset_command;     /* 0,1,2 */
3155                                chm_post_app_event(p_chm,&p_chm->reset_evt);
3156                                break;
3157                        case UDTA_CONNECT:
3158                                if (!p_app->settings.activated)
3159                                {
3160                                        BDBG_WRN(("CONNECT message received - activating\n"));
3161                                }
3162                                p_chm->activate_evt.type = eCHM_EVT_ACTIVATION;
3163                                p_chm->activate_evt.id = 1;     /* activate */
3164                                chm_post_app_event(p_chm,&p_chm->activate_evt);
3165                                break;
3166                        case UDTA_DISCONNECT:
3167                                p_chm->activate_evt.type = eCHM_EVT_ACTIVATION;
3168                                p_chm->activate_evt.id = 0;     /* deactivate */
3169                                chm_post_app_event(p_chm,&p_chm->activate_evt);
3170                                break;
3171                        case UDTA_SITE_ANNOUNCEMENT:
3172                                udta_parse_site_announcement_subcommand(&pst, &usite);
3173                                p_chm->location_evt.type = eCHM_EVT_LOCATION;
3174                                p_chm->location_evt.id = usite.site_code;
3175                                chm_post_app_event(p_chm,&p_chm->location_evt);
3176
3177                                parsed_len = pst.bits.bindex >> 3;
3178                                while(parsed_len < umessage.message_length){
3179                                        udta_parse_descriptor(&pst, &udescriptor);
3180                                        if(UDTA_PHONE_NUMBER_DESCRIPTOR == udescriptor.descriptor_tag){
3181                                                uphone_descriptor.length = udescriptor.descriptor_lenght;
3182                                                udta_parse_phone_number_descriptor(&pst, &uphone_descriptor);
3183                                                uphone_descriptor.phone_number_string[uphone_descriptor.length] = 0; // ensure string terminator
3184                                                strcpy(p_chm->phone_evt.data,uphone_descriptor.phone_number_string);
3185                                        p_chm->phone_evt.type = eCHM_EVT_PHONENUMBER;
3186                                                chm_post_app_event(p_chm,(chm_event_t*)&p_chm->phone_evt);
3187                                        }else{
3188                                                udta_skip_descriptor(&pst, &udescriptor);
3189                                        }
3190                                        parsed_len = pst.bits.bindex >> 3;
3191                                }
3192                                break;
3193                        case UDTA_KEY_TABLE:
3194                                p_chm->key_table_cnt++;
3195                                udta_parse_key_table_subcommand(&pst, &keyt);
3196                                for (idx = 0; idx < keyt.number_of_global_keys; ++idx)
3197                                {
3198                                        udta_parse_encrypted_global_key(&pst, &egk);
3199                                        /* TODO Put into EGK structure */
3200                                }
3201                                /* TODO Send key table to application for storage.  */
3202                                break;
3203                        case UDTA_EAS_FILTER_CONTROL:
3204                                p_chm->eas_filter_cnt++;
3205                                udta_parse_eas_filter_control_subcommand(&pst, &efc);
3206                                /* TODO Send filter control information to application for storage.  */
3207                                break;
3208                        default:
3209                                udta_skip_subcommand(&pst, &usubcommand);
3210                                break;
3211                        }
3212                }
3213                break;
3214        default:
3215                BDBG_WRN(("#### Unsupported MSP Command 0x%02x #### \n", umessage.message_type));
3216                break;
3217        }
3218
3219ExitFunc:
3220        return(void*)(p_chm->emm_buf);
3221}
3222#else
3223void* chm_smessage_emm_callback(void * context, size_t size)
3224{
3225        chm_mgr_t * p_chm = (chm_mgr_t*)context;
3226
3227        return(void*)(p_chm->emm_buf);
3228}
3229#endif
3230
3231/******************************************************************************
3232 * INPUTS:      context
3233 * OUTPUTS:     none.
3234 * RETURNS:     none
3235 * FUNCTION:    message_callback
3236 * DESCRIPTION: Callback function normally called when a complete message has
3237 *              been received and passed the filter criteria.
3238 ******************************************************************************/
3239
3240void * chm_smessage_stt_callback(void * context, size_t size)
3241{
3242        chm_mgr_t * p_chm;
3243        struct tm utc_time;
3244        struct timeval tv;
3245
3246        p_chm = (chm_mgr_t*)context;
3247
3248        p_chm->time_evt.type = eCHM_EVT_TIME;
3249
3250        if (SI_STT_parse(p_chm->stt_buf) != SI_SUCCESS)
3251        {
3252                BDBG_WRN(("%s SI_STT_parse failed\n",__FUNCTION__));
3253                return(void*)p_chm->stt_buf;
3254        }
3255
3256        p_chm->stt_cnt++;
3257
3258        /* current platform seconds when STT was received */
3259        GETTIMEOFDAY(&tv);
3260
3261        /* Current UTC time according to STT */
3262        p_chm->time_evt.system_time = SI_STT_Get_Sys_Time() - SI_STT_Get_GPS_UTC_Offset();
3263        p_chm->time_evt.system_offset = tv.tv_sec;
3264        p_chm->time_evt.utc_offset = SI_STT_Get_GPS_UTC_Offset();
3265
3266        chm_post_app_event(p_chm,(chm_event_t*)&p_chm->time_evt);
3267
3268        utctime(p_chm->time_evt.system_time,&utc_time);
3269        BDBG_WRN(("STT UTC = %2d/%2d/%4d %2d:%2d:%2d\n",
3270                          utc_time.tm_mon + 1,utc_time.tm_mday,utc_time.tm_year + 1980, 
3271                          utc_time.tm_hour,utc_time.tm_min,utc_time.tm_sec));
3272        return(void*)p_chm->stt_buf;
3273}
3274
3275/*
3276   Destination for cvt parser so the actual data would not be changed while
3277   it is being processed by another thread
3278 */
3279static struct cvt_info_t cvt_info;
3280
3281/******************************************************************************
3282 * INPUTS:      context
3283 * OUTPUTS:     none.
3284 * RETURNS:     none
3285 * FUNCTION:    message_callback
3286 * DESCRIPTION: Callback function normally called when a complete message has
3287 *              been received and passed the filter criteria.
3288 ******************************************************************************/
3289
3290void * chm_smessage_cvt_callback(void * context, size_t size)
3291{
3292        chm_mgr_t * p_chm = (chm_mgr_t*)context;
3293        bapp_t *p_app;
3294        int res,i;
3295        unsigned short vch_num;
3296
3297        p_app = (bapp_t*)p_chm->p_app;
3298
3299        BDBG_ERR(("#### CVT Event ####\n"));
3300
3301        ch_map_get_vch_num(bapp_cur_ch_map(p_app),&vch_num);
3302
3303        if (vch_num == 0)
3304        {
3305                BDBG_WRN(("%s No channels in map.\n",__FUNCTION__));
3306                goto ExitFunc;
3307        }
3308        res = cvt_parse(p_chm->cvt_buf, size, &cvt_info);
3309        if (res != 0)
3310        {
3311                BDBG_WRN(("#### CVT Inavlid.####, res=%d\n", res));
3312                goto ExitFunc;
3313        }
3314
3315        p_chm->cvt_cnt++;
3316
3317#ifdef  CVT_DEBUG
3318        BDBG_WRN(("protocol_version                = %d", cvt_info.protocol_version));
3319        BDBG_WRN(("configuration_count_change      = %d", cvt_info.configuration_count_change));
3320        BDBG_WRN(("vendor_id                       = %d (0x%08x)", cvt_info.vendor_id, cvt_info.vendor_id));
3321        BDBG_WRN(("hardware_version_id             = %d (0x%08x)", cvt_info.hardware_version_id, cvt_info.hardware_version_id));
3322        BDBG_WRN(("location_type                   = %d", cvt_info.location_type));
3323        BDBG_WRN(("source_ID                       = %d", cvt_info.source_ID));
3324        BDBG_WRN(("frequency_vector                = %d (0x%04x)", cvt_info.frequency_vector, cvt_info.frequency_vector));
3325        BDBG_WRN(("modulation_type                 = %d", cvt_info.modulation_type));
3326        BDBG_WRN(("program_number                  = %d (0x%04x)", cvt_info.program_number & 0xffff, cvt_info.program_number & 0xffff));
3327        BDBG_WRN(("pid                             = %d (0x%04x)", cvt_info.pid, cvt_info.pid));
3328        BDBG_WRN(("code_file_name_length           = %d", cvt_info.code_file_name_length));
3329        cvt_info.code_file_name[cvt_info.code_file_name_length] = '\0';
3330        BDBG_WRN(("code_file_name                  = %s", cvt_info.code_file_name));
3331#endif
3332        if (cvt_info.vendor_id != p_chm->vendor_id)
3333        {
3334                BDBG_ERR(("#### CVT Vendor ID mismatch (0x%08x != 0x%08x) ####\n",cvt_info.vendor_id, p_chm->vendor_id));
3335                goto ExitFunc;
3336        }
3337
3338        if (cvt_info.hardware_version_id != p_chm->hardware_version_id)
3339        {
3340                BDBG_ERR(("#### CVT Vendor ID mismatch (0x%08x != 0x%08x) ####\n",cvt_info.vendor_id, p_chm->vendor_id));
3341                goto ExitFunc;
3342        }
3343
3344        BDBG_WRN(("#### CVT Got Vendor ID  (0x%08x) ####\n",cvt_info.vendor_id));
3345        if (true == p_chm->cvt_valid)
3346        {
3347                if (cvt_info.configuration_count_change == p_chm->cvt.configuration_count_change)
3348                {
3349                        BDBG_WRN(("configuration_count_change %d:%d", cvt_info.configuration_count_change, p_chm->cvt.configuration_count_change));
3350                        goto ExitFunc;
3351                }
3352
3353                i = 0;
3354                if (cvt_info.code_file_name_length == p_chm->cvt.code_file_name_length)
3355                {
3356                        for (i = 0; i < cvt_info.code_file_name_length; ++i)
3357                        {
3358                                if (cvt_info.code_file_name[i] != p_chm->cvt.code_file_name[i])
3359                                {
3360                                        break;
3361                                }
3362                        }
3363                }
3364                if (i == cvt_info.code_file_name_length)
3365                {
3366                        BDBG_WRN(("CVT file names match"));
3367                        goto ExitFunc;
3368                }
3369        }
3370
3371        if (p_chm->cmd == eCHM_HUNTING)
3372                p_chm->cmd = eCHM_CANCEL;
3373
3374        if (p_chm->num_freq == 0)
3375        {
3376                bapp_freq_table_get(p_chm->fe_type,(const unsigned int **)&(p_chm->freq_table),&(p_chm->num_freq));
3377        }
3378
3379        if (p_chm->num_freq == 0)
3380        {
3381                BDBG_WRN(("%s:%d p_chm->num_freq = %d\n",__FUNCTION__,__LINE__,p_chm->num_freq));
3382                goto ExitFunc;
3383        }
3384       
3385        /* copy structure to channel manager and mark cvt as valid */
3386        bapp_util_memcpy(&(p_chm->cvt), &cvt_info, sizeof(struct cvt_info_t));
3387        p_chm->cvt_valid = true;
3388        p_chm->download_evt.type = eCHM_EVT_DOWNLOAD;
3389        p_chm->download_evt.id = (p_chm->select_idx * (100/p_chm->num_freq))/p_chm->num_freq;
3390        chm_post_app_event_cb(p_chm,&p_chm->download_evt);
3391        ExitFunc:
3392        return(void*)p_chm->cvt_buf;
3393}
3394/*
3395Summary:
3396Get the STT. return non-zero on failure
3397 */
3398
3399static int chm_stt_start(chm_mgr_t *p_chm,              /* Channel manager reference */
3400                                                 unsigned short network_pid)
3401{
3402        int cerr;
3403        smessage_stream_params_t params;
3404
3405        cerr = eCHM_ERR_OK;
3406        BDBG_MSG(("%s:%d (0x%04x)",__FUNCTION__, __LINE__,network_pid));
3407
3408        chm_stt_stop(p_chm);
3409
3410        p_chm->stt_msg = smessage_open(smessage_format_psi);
3411        if (NULL == p_chm->stt_msg)
3412        {
3413                BDBG_ERR(("%s:%d",__FILE__, __LINE__));
3414                cerr = eCHM_ERR_FAILED;
3415                goto ExitFunc;
3416        }
3417        smessage_stream_params_init(&params, p_chm->stt_msg);
3418        params.band = p_chm->band;
3419        params.pid = (uint16_t)network_pid;
3420        params.filter.coef[0] = 0xC5;
3421        params.filter.mask[0] = 0x00;
3422        /* All PSIP tables have protocol_version which must be = 0 */
3423        params.filter.coef[3] = 0x00;   /* protocol_version */
3424        params.filter.mask[3] = 0x00;
3425        params.buffer = p_chm->stt_buf;
3426        params.buffer_size = STT_BUF_LEN;
3427        /* processing is done in callback */
3428        params.data_ready_callback = chm_smessage_stt_callback;
3429        params.overflow = NULL;
3430        params.callback_context = (void *)p_chm;
3431        BDBG_WRN(("%s\n",__FUNCTION__));
3432        if (b_ok != smessage_start(&params, p_chm->stt_msg))
3433        {
3434                BDBG_ERR(("%s:%d",__FILE__, __LINE__));
3435                cerr = eCHM_ERR_FAILED;
3436        }
3437        ExitFunc:
3438        return cerr;
3439}
3440/*
3441Summary:
3442Stop checking for EMM messages. return non-zero on failure
3443 */
3444
3445static void chm_emm_stop(chm_mgr_t *p_chm               /* Channel manager reference */
3446                                                )
3447{
3448        if (NULL != p_chm->emm_msg)
3449        {
3450                if (b_ok != smessage_stop(p_chm->emm_msg))
3451                {
3452                        BDBG_ERR(("%s:%d",__FUNCTION__, __LINE__));
3453                        return;
3454                }
3455                smessage_close(p_chm->emm_msg);
3456                p_chm->emm_msg = NULL;
3457        }
3458}
3459/*
3460Summary:
3461Start checking for EMM messages. return non-zero on failure
3462 */
3463
3464static int chm_emm_start(chm_mgr_t *p_chm,              /* Channel manager reference */
3465                                                 unsigned short emm_pid)
3466{
3467        int cerr;
3468        smessage_stream_params_t params;
3469
3470        cerr = eCHM_ERR_OK;
3471        BDBG_MSG(("%s:%d (0x%04x)",__FUNCTION__, __LINE__,emm_pid));
3472
3473        chm_emm_stop(p_chm);
3474
3475        p_chm->emm_msg = smessage_open(smessage_format_psi);
3476        if (NULL == p_chm->emm_msg)
3477        {
3478                BDBG_ERR(("%s:%d",__FILE__, __LINE__));
3479                cerr = eCHM_ERR_FAILED;
3480                goto ExitFunc;
3481        }
3482        smessage_stream_params_init(&params, p_chm->emm_msg);
3483        params.band = p_chm->band;
3484        params.pid = (uint16_t)emm_pid;
3485        params.filter.coef[0] = 0x80;
3486        params.filter.mask[0] = 0x0f;
3487        /* filter on byte 2 */
3488        params.filter.coef[1] = 0x00;
3489        params.filter.mask[1] = 0x1f;
3490#if 0
3491
3492        /* All PSIP tables have protocol_version which must be = 0 */
3493        params.filter.coef[3] = 0x00;   /* protocol_version */
3494        params.filter.mask[3] = 0x00;
3495#endif
3496        params.buffer = p_chm->emm_buf;
3497        params.buffer_size = EMM_BUF_LEN;
3498        /* processing is done in callback */
3499        params.data_ready_callback = chm_smessage_emm_callback;
3500        params.overflow = NULL;
3501        params.callback_context = (void *)p_chm;
3502        if (b_ok != smessage_start(&params, p_chm->emm_msg))
3503        {
3504                BDBG_ERR(("%s:%d",__FILE__, __LINE__));
3505                cerr = eCHM_ERR_FAILED;
3506        }
3507        ExitFunc:
3508        return cerr;
3509}
3510
3511/*
3512Summary:
3513Tune to the current frequency.
3514 */
3515static int chm_tune_freq(chm_mgr_t *p_chm,unsigned int freq_hz,unsigned int freq_idx)
3516{
3517        bapp_t *p_app = (bapp_t*)p_chm->p_app;
3518        mms_t mms;
3519        unsigned int tune_ticks;
3520        BDBG_WRN(("%s: freq_hz=%d, last_freq_hz=%d\n",__FUNCTION__, freq_hz, p_chm->last_freq_hz));
3521
3522        if (p_chm->force_tune)
3523        {
3524                p_chm->last_freq_hz = 0;
3525                p_chm->force_tune = false;
3526        }
3527
3528        if (p_chm->last_freq_hz != freq_hz)
3529        {
3530                chm_stop_decode(p_chm);
3531
3532                BDBG_WRN(("Tune to frequency = %d\n",freq_hz));
3533
3534                tune_ticks = bapp_task_getticks();
3535
3536
3537                if (bapp_tune_lock(p_chm->tune,freq_hz) != eBAPP_RESULT_OK)
3538                {
3539                        chm_send_status(p_chm,freq_hz,false);
3540
3541                        return eCHM_ERR_FAILED;
3542                }
3543
3544                tune_ticks = bapp_task_getticks() - tune_ticks;
3545                p_chm->status_evt.type = eCHM_EVT_STATUS;
3546                p_chm->status_evt.id = eCHM_STATUS_TUNE_MS;
3547                p_chm->status_evt.ticks = TICKS_TO_MS(tune_ticks);
3548                chm_post_app_event(p_chm,(chm_event_t*)&p_chm->status_evt);
3549
3550                p_chm->last_freq_hz = freq_hz;
3551        } 
3552        else
3553        {
3554                BDBG_WRN(("Already tuned to frequency = %d\n",freq_hz));
3555        }
3556        p_chm->status_evt.ticks = TICKS_TO_MS((bapp_task_getticks() - tune_ticks));
3557        chm_post_app_event(p_chm,(chm_event_t*)&p_chm->status_evt);
3558
3559        BDBG_ERR(("%s:%d\n",__FUNCTION__, __LINE__));
3560        chm_send_status(p_chm,freq_hz,true);
3561
3562        return eCHM_ERR_OK;
3563}
3564
3565/*
3566Summary:
3567Rotate audio pids.
3568 */
3569
3570static int chm_rotate_audio(chm_mgr_t *p_chm)
3571{
3572#ifdef CONFIG_HAS_AUDIO
3573        bapp_t *p_app = (bapp_t*)p_chm->p_app;
3574        vch_t vch;
3575        st_t st;
3576        freq_t freq;
3577
3578        if (!p_chm->curr_stream || !p_chm->curr_stream->stream)
3579                return eCHM_ERR_FAILED;
3580
3581        if (!ch_map_get_current(bapp_cur_ch_map(p_app),&vch,&st,&freq))
3582        {
3583                BDBG_WRN(("%s Invalid current channel or map.\n",__FUNCTION__));
3584                return 0;
3585        }
3586
3587        BDBG_WRN(("%s from 0x%04x to 0x%04x\n",__FUNCTION__,p_chm->mpeg[CURR_CH].audio[0].pid, vch.audio_pid[vch.cur_audio]));
3588
3589        if (p_chm->av && (p_chm->mpeg[CURR_CH].audio[0].pid != 0))
3590        {
3591                BDBG_WRN(("baudio_decode_stop  0x%04x\n",p_chm->mpeg[CURR_CH].audio[0].pid));
3592                baudio_decode_stop(p_chm->av);
3593        }
3594
3595        p_chm->mpeg[CURR_CH].audio[0].pid = vch.audio_pid[vch.cur_audio];
3596        if (p_chm->av)
3597        {
3598                if (p_chm->mpeg[CURR_CH].audio[0].pid != 0)
3599                {
3600                        BDBG_WRN(("baudio_decode_start  0x%04x\n",p_chm->mpeg[CURR_CH].audio[0].pid));
3601                        if (baudio_decode_start(p_chm->av, (void *)1, p_chm->curr_stream->stream))
3602                        {
3603                                BDBG_WRN(("baudio_decode_start failed\n"));
3604                                return eCHM_ERR_FAILED;
3605                        }
3606                }
3607        }
3608#endif
3609        return eCHM_ERR_OK;
3610}
3611
3612/*
3613Summary:
3614        Open a stream given an mpeg program structure.
3615 */
3616static int chm_start_stream(chm_mgr_t *p_chm, chm_stream_t *p_stream,bstream_mpeg *p_mpeg)
3617{
3618        BDBG_ASSERT(p_stream);
3619        BDBG_ASSERT(p_mpeg);
3620       
3621        if (p_stream->stream)
3622        {
3623                bstream_close(p_stream->stream);
3624                p_stream->stream = NULL;
3625        }
3626
3627        p_stream->stream = bstream_open(p_chm->band,p_mpeg);
3628        if (p_stream->stream)
3629        {
3630                p_stream->freq_hz = p_chm->last_freq_hz;
3631                p_stream->pid = p_mpeg->video[0].pid;
3632        }
3633        return (p_stream->stream) ? eCHM_ERR_OK : eCHM_ERR_FAILED;
3634}
3635
3636
3637/*
3638Summary:
3639        Close the stream.
3640 */
3641static void chm_stop_stream(chm_mgr_t *p_chm, chm_stream_t *p_stream)
3642{
3643        BDBG_ASSERT(p_stream);
3644       
3645        if (p_stream->stream)
3646        {
3647                bstream_close(p_stream->stream);
3648                p_stream->stream = NULL;
3649                p_stream->pid = 0;
3650        }
3651}
3652/*
3653Summary:
3654        Stop unused stream.
3655 */
3656static void chm_stop_unused_streams(chm_mgr_t *p_chm)
3657{
3658        int mpeg_idx,stream_idx;
3659        bool match;
3660       
3661        for (stream_idx = 0; stream_idx < BSETTOP_MAX_STREAMS; ++stream_idx)
3662        {
3663                match = false;
3664                for (mpeg_idx = 0; mpeg_idx < BSETTOP_MAX_STREAMS; ++mpeg_idx)
3665                {
3666                        if (p_chm->mpeg[mpeg_idx].video[0].pid == p_chm->chm_stream[stream_idx].pid)
3667                        {
3668                                match = true;
3669                                continue;
3670                        }
3671                }
3672                if (!match)
3673                {
3674                        chm_stop_stream(p_chm,&(p_chm->chm_stream[stream_idx]));
3675                }
3676
3677        }
3678}
3679/*
3680Summary:
3681        Find the stream with this PID .
3682 */
3683static chm_stream_t *chm_find_stream(chm_mgr_t *p_chm, unsigned short pid)
3684{
3685        int stream_idx;
3686        BDBG_ASSERT(p_chm);
3687       
3688        for (stream_idx = 0; stream_idx < BSETTOP_MAX_STREAMS; ++stream_idx)
3689        {
3690                if (pid == p_chm->chm_stream[stream_idx].pid)
3691                {
3692                        return &(p_chm->chm_stream[stream_idx]);
3693                }
3694        }
3695        return NULL;
3696}
3697/*
3698Summary:
3699        Find an unused stream.
3700 */
3701static chm_stream_t *chm_find_unused_stream(chm_mgr_t *p_chm)
3702{
3703        int stream_idx;
3704        BDBG_ASSERT(p_chm);
3705       
3706        for (stream_idx = 0; stream_idx < BSETTOP_MAX_STREAMS; ++stream_idx)
3707        {
3708                if (p_chm->chm_stream[stream_idx].stream == NULL)
3709                {
3710                        return &(p_chm->chm_stream[stream_idx]);
3711                }
3712        }
3713        return NULL;
3714}
3715
3716/*
3717Summary:
3718Start audio and video decode.
3719Description:
3720Handle tuning to the current channel. Returns non-zero on failure.
3721 */
3722static int chm_start_decode(chm_mgr_t *p_chm, bool force_restart)
3723{
3724        bapp_t *p_app = (bapp_t*)p_chm->p_app;
3725        chm_stream_t *tmp_stream;
3726
3727        if ((p_chm->mpeg[CURR_CH].audio[0].pid == 0x0000) && (p_chm->mpeg[CURR_CH].video[0].pid == 0x0000))
3728        {
3729                BDBG_WRN(("%s (0x%04x,0x%04x,0x%04x,%d) failed \n",
3730                                  __func__,p_chm->mpeg[CURR_CH].video[0].pid,p_chm->mpeg[CURR_CH].pcr_pid,
3731                                  p_chm->mpeg[CURR_CH].audio[0].pid,p_chm->band));
3732                return eCHM_ERR_FAILED;
3733        }
3734
3735        if (p_chm->mpeg[CURR_CH].video[0].pid == 0x0000)
3736        {
3737                /* JPF TODO MUTE Video to black in case we are showing last frame on channel change. */
3738        }
3739
3740        /* Stop the current decode (but not the streams) */
3741        chm_stop_decode(p_chm);
3742       
3743        /* Handle audio only decode */
3744        if (p_chm->av && (p_chm->mpeg[CURR_CH].audio[0].pid != 0x0000) && (p_chm->mpeg[CURR_CH].video[0].pid == 0x0000))
3745        {
3746                BDBG_WRN(("%s (0x%04x,0x%04x,0x%04x,%d) audio only decode \n",
3747                                  __func__,p_chm->mpeg[CURR_CH].video[0].pid,p_chm->mpeg[CURR_CH].pcr_pid,
3748                                  p_chm->mpeg[CURR_CH].audio[0].pid,p_chm->band));
3749
3750                chm_stop_stream(p_chm,&(p_chm->chm_stream[CURR_CH]));
3751                chm_stop_stream(p_chm,&(p_chm->chm_stream[PREV_CH]));
3752                chm_stop_stream(p_chm,&(p_chm->chm_stream[NEXT_CH]));
3753
3754                if (chm_start_stream(p_chm,&(p_chm->chm_stream[CURR_CH]),&(p_chm->mpeg[CURR_CH])))
3755                {
3756                        BDBG_WRN(("chm_start_stream failed\n"));
3757                        return eCHM_ERR_FAILED;
3758                }
3759               
3760                p_chm->curr_stream = &(p_chm->chm_stream[CURR_CH]);
3761
3762
3763                if (bapp_audio_start(p_chm->av, p_chm->curr_stream->stream))
3764                {
3765                        BDBG_WRN(("baudio_decode_start failed\n"));
3766                        return eCHM_ERR_FAILED;
3767                }
3768                p_chm->decoding_audio = true;
3769                return eCHM_ERR_OK;
3770        }
3771
3772        /* Check if all streams need to be restarted */
3773        if (force_restart)
3774        {
3775                chm_stop_stream(p_chm,&(p_chm->chm_stream[CURR_CH]));
3776                chm_stop_stream(p_chm,&(p_chm->chm_stream[PREV_CH]));
3777                chm_stop_stream(p_chm,&(p_chm->chm_stream[NEXT_CH]));
3778
3779                if (chm_start_stream(p_chm,&(p_chm->chm_stream[CURR_CH]),&(p_chm->mpeg[CURR_CH])))
3780                {
3781                        BDBG_WRN(("chm_start_stream failed\n"));
3782                        return eCHM_ERR_FAILED;
3783                }
3784               
3785                p_chm->curr_stream = &(p_chm->chm_stream[CURR_CH]);
3786
3787                if (p_chm->mpeg[NEXT_CH].video[0].pid != 0x0000)
3788                {
3789                        if (chm_start_stream(p_chm,&(p_chm->chm_stream[NEXT_CH]),&(p_chm->mpeg[NEXT_CH])))
3790                        {
3791                                BDBG_WRN(("chm_start_stream next failed\n"));
3792                        }
3793                }
3794
3795                if (p_chm->mpeg[PREV_CH].video[0].pid != 0x0000)
3796                {
3797                        if (chm_start_stream(p_chm,&(p_chm->chm_stream[PREV_CH]),&(p_chm->mpeg[PREV_CH])))
3798                        {
3799                                BDBG_WRN(("chm_start_stream prev failed\n"));
3800                        }
3801                }
3802        }
3803        else
3804        {
3805                chm_stop_unused_streams(p_chm);
3806
3807                p_chm->curr_stream = chm_find_stream(p_chm,p_chm->mpeg[CURR_CH].video[0].pid);
3808
3809                if (p_chm->curr_stream == NULL)
3810                {
3811                        if (chm_start_stream(p_chm,&(p_chm->chm_stream[CURR_CH]),&(p_chm->mpeg[CURR_CH])))
3812                        {
3813                                BDBG_WRN(("chm_start_stream current failed\n"));
3814                                return eCHM_ERR_FAILED;
3815                        }
3816                        p_chm->curr_stream = &(p_chm->chm_stream[CURR_CH]);
3817                }
3818
3819                if (p_chm->mpeg[NEXT_CH].video[0].pid != 0x0000)
3820                {
3821                        tmp_stream = chm_find_stream(p_chm,p_chm->mpeg[NEXT_CH].video[0].pid);
3822
3823                        if (tmp_stream == NULL)
3824                        {
3825                                tmp_stream = chm_find_unused_stream(p_chm);
3826
3827                                if (tmp_stream)
3828                                {
3829                                        if (chm_start_stream(p_chm,tmp_stream,&(p_chm->mpeg[NEXT_CH])))
3830                                        {
3831                                                BDBG_WRN(("chm_start_stream next failed\n"));
3832                                        }
3833                                }
3834                        }
3835                }
3836
3837                if (p_chm->mpeg[PREV_CH].video[0].pid != 0x0000)
3838                {
3839                        tmp_stream = chm_find_stream(p_chm,p_chm->mpeg[PREV_CH].video[0].pid);
3840
3841                        if (tmp_stream == NULL)
3842                        {
3843                                tmp_stream = chm_find_unused_stream(p_chm);
3844
3845                                if (tmp_stream)
3846                                {
3847                                        if (chm_start_stream(p_chm,tmp_stream,&(p_chm->mpeg[PREV_CH])))
3848                                        {
3849                                                BDBG_WRN(("chm_start_stream next failed\n"));
3850                                        }
3851                                }
3852                        }
3853                }
3854        }
3855
3856        if (!p_chm->curr_stream)
3857        {
3858                BDBG_WRN(("%s current stream NULL\n",__FUNCTION__));
3859                return eCHM_ERR_FAILED;
3860        }
3861
3862        BDBG_WRN(("%s(0x%04x,0x%04x,0x%04x,%d)\n",
3863                          __func__,p_chm->mpeg[CURR_CH].video[0].pid,p_chm->mpeg[CURR_CH].pcr_pid,
3864                          p_chm->mpeg[CURR_CH].audio[0].pid,p_chm->band));
3865
3866        if (bapp_video_start(p_chm->av, p_chm->curr_stream->stream))
3867        {
3868                BDBG_WRN(("bdecode_start failed\n"));
3869                return eCHM_ERR_FAILED;
3870        }
3871        p_chm->decoding_video = true;
3872       
3873        if (p_chm->av && (p_chm->mpeg[CURR_CH].audio[0].pid != 0))
3874        {
3875                if (bapp_audio_start(p_chm->av, p_chm->curr_stream->stream))
3876                {
3877                        BDBG_WRN(("baudio_decode_start failed\n"));
3878                        return eCHM_ERR_FAILED;
3879                }
3880        }
3881        p_chm->decoding_audio = true;
3882        return eCHM_ERR_OK;
3883}
3884/*
3885Summary:
3886Stop audio and video decode.
3887 */
3888static int chm_stop_decode(chm_mgr_t *p_chm)
3889{
3890        bapp_t *p_app = (bapp_t*)p_chm->p_app;
3891
3892        chm_eas_stop(p_chm);
3893        chm_cvt_stop(p_chm);
3894        chm_nit_stop(p_chm);
3895        chm_ntt_stop(p_chm);
3896        chm_svct_stop(p_chm);
3897        chm_emm_stop(p_chm);
3898        chm_cat_stop(p_chm);
3899
3900        if (p_chm->decoding_video)
3901                bapp_video_stop(p_chm->av);
3902        if (p_chm->decoding_audio)
3903                bapp_audio_stop(p_chm->av);
3904        p_chm->decoding_video = false;
3905        p_chm->decoding_audio = false;
3906
3907        return 0;
3908}
3909/*
3910Summary:
3911Tune to the current frequency and enter steady channel processing state..
3912Description:
3913Tune to the current frequency and enter steady channel processing state..
3914 */
3915static int chm_tune_current(chm_mgr_t *p_chm)
3916{
3917        unsigned int freq_hz;
3918        bapp_t *p_app = (bapp_t*)p_chm->p_app;
3919
3920        if (chm_check_cancel(p_chm))
3921                return eCHM_ERR_CANCELED;
3922
3923        chm_eas_stop(p_chm);
3924        chm_cvt_stop(p_chm);
3925        chm_nit_stop(p_chm);
3926        chm_ntt_stop(p_chm);
3927        chm_svct_stop(p_chm);
3928        chm_emm_stop(p_chm);
3929
3930        /* don't stop video decode to support fast channel change feature */
3931#ifdef CONFIG_HAS_AUDIO
3932        if (p_chm->av)
3933                baudio_decode_stop(p_chm->av);
3934#endif
3935
3936        freq_hz = p_chm->freq.freq_khz * 1000;
3937
3938        if (chm_tune_freq(p_chm,freq_hz,p_chm->freq.idx) != 0)
3939        {
3940                BDBG_WRN(("chm_tune_freq failed, try to retune and reacq"));
3941                /* force to re-tune */
3942                p_chm->force_tune = true;
3943                if (chm_tune_freq(p_chm,freq_hz,p_chm->freq.idx) == 0)
3944                {
3945                        return eCHM_ERR_OK;
3946                }
3947                BDBG_WRN(("chm_tune_freq failed\n"));
3948                return eCHM_ERR_FAILED;
3949        }
3950
3951        return eCHM_ERR_OK;
3952}
3953/*
3954Summary:
3955Tune to the current frequency and get the VCT.
3956Description:
3957Tune to the current frequency and get the VCT. Returns non-zero on failure.
3958 */
3959
3960static int chm_config_mpeg(chm_mgr_t *p_chm, vch_t *p_vch)
3961{
3962        unsigned short ch_num;
3963        vch_t tmp_vch;
3964        st_t tmp_st; 
3965        freq_t tmp_freq;
3966        bapp_t *p_app = (bapp_t*)p_chm->p_app;
3967        bapp_util_memset(&(p_chm->mpeg[CURR_CH]),0,sizeof(bstream_mpeg));
3968        bapp_util_memset(&(p_chm->mpeg[PREV_CH]),0,sizeof(bstream_mpeg));
3969        bapp_util_memset(&(p_chm->mpeg[NEXT_CH]),0,sizeof(bstream_mpeg));
3970
3971        p_chm->mpeg[CURR_CH].pcr_pid = p_vch->pcr_pid;
3972        p_chm->mpeg[CURR_CH].video[0].pid = p_vch->video_pid;
3973        p_chm->mpeg[CURR_CH].video[0].format = p_vch->video_type;
3974        p_chm->mpeg[CURR_CH].audio[0].pid = p_vch->audio_pid[p_vch->cur_audio];
3975        p_chm->mpeg[CURR_CH].audio[0].format = p_vch->audio_type[p_vch->cur_audio];
3976
3977        if (p_chm->mpeg[CURR_CH].audio[0].pid == 0)
3978        {
3979                BDBG_WRN(("### All audio PIDs are 0x0000 ###\n"));
3980        }
3981
3982        ch_num = p_vch->ch_num;
3983        if (ch_map_set_next(bapp_cur_ch_map(p_app)))
3984        {
3985                if (ch_map_get_current(bapp_cur_ch_map(p_app),&tmp_vch,&tmp_st, &tmp_freq))
3986                {
3987                        if (tmp_vch.freq_idx == p_vch->freq_idx)
3988                        {
3989                                p_chm->mpeg[NEXT_CH].video[0].pid = tmp_vch.video_pid;
3990                                p_chm->mpeg[NEXT_CH].video[0].format = tmp_vch.video_type;
3991                                p_chm->mpeg[NEXT_CH].audio[0].pid = tmp_vch.audio_pid[tmp_vch.cur_audio];
3992                                p_chm->mpeg[NEXT_CH].pcr_pid = tmp_vch.pcr_pid;
3993                                p_chm->mpeg[NEXT_CH].audio[0].format =  tmp_vch.audio_type[tmp_vch.cur_audio];
3994                        }
3995                }
3996        }
3997
3998        ch_map_set_ch(bapp_cur_ch_map(p_app),ch_num);
3999        if (ch_map_set_prev(bapp_cur_ch_map(p_app)))
4000        {
4001                if (ch_map_get_current(bapp_cur_ch_map(p_app),&tmp_vch,&tmp_st, &tmp_freq))
4002                {
4003                        if (tmp_vch.freq_idx == p_vch->freq_idx)
4004                        {
4005                                p_chm->mpeg[PREV_CH].video[0].pid = tmp_vch.video_pid;
4006                                p_chm->mpeg[PREV_CH].video[0].format = tmp_vch.video_type;
4007                                p_chm->mpeg[PREV_CH].audio[0].pid = tmp_vch.audio_pid[tmp_vch.cur_audio];
4008                                p_chm->mpeg[PREV_CH].pcr_pid = tmp_vch.pcr_pid;
4009                                p_chm->mpeg[PREV_CH].audio[0].format = tmp_vch.audio_type[tmp_vch.cur_audio];
4010                        }
4011                }
4012        }
4013
4014        ch_map_set_ch(bapp_cur_ch_map(p_app),ch_num);
4015
4016        return 0;
4017}
4018
4019/*
4020Summary:
4021Tune to the current frequency and enter steady channel processing state..
4022Description:
4023Tune to the current frequency and enter steady channel processing state..
4024 */
4025int chm_tune(chm_mgr_t *p_chm)
4026{
4027        int result = eCHM_ERR_FAILED;
4028        bool force_restart = false;
4029
4030        bapp_t *p_app = (bapp_t*)p_chm->p_app;
4031
4032        BDBG_WRN(("%s entry (line %d)\n",__FUNCTION__,__LINE__));
4033
4034        if (chm_check_cancel(p_chm))
4035        {
4036                BDBG_WRN(("%s cancel detected at line %d\n",__FUNCTION__,__LINE__));
4037                return eCHM_ERR_CANCELED;
4038        }
4039
4040        if (!ch_map_get_current(bapp_cur_ch_map(p_app),&p_chm->vch,&p_chm->st,&p_chm->freq))
4041        {
4042                BDBG_WRN(("%s ch_map_get_current failed\n",__FUNCTION__));
4043                return eCHM_ERR_FAILED;
4044        }
4045        p_chm->vch.cur_audio = 0;
4046        force_restart = ((p_chm->freq.freq_khz * 1000) == p_chm->last_freq_hz) ? false : true;
4047
4048        if ((result = chm_tune_current(p_chm)) != eCHM_ERR_OK)
4049        {
4050                BDBG_WRN(("%s chm_tune_current failed\n",__FUNCTION__));
4051                return result;
4052        }
4053
4054#ifdef  HAS_VBI
4055        if (p_chm->pscte_127)
4056        {
4057                scte_127_reset(p_chm->pscte_127);
4058                scte_127_enable(p_chm->pscte_127, false);
4059                chm_scte127_stop(p_chm);
4060        }
4061#endif
4062
4063        if (chm_check_cancel(p_chm))
4064        {
4065                BDBG_WRN(("%s cancel detected at line %d\n",__FUNCTION__,__LINE__));
4066                return eCHM_ERR_CANCELED;
4067        }
4068
4069        /* if no pids exist get them */
4070        if ((p_chm->vch.video_pid == 0) && (p_chm->vch.audio_pid[0] == 0) && (p_chm->vch.pcr_pid == 0))
4071        {
4072                BDBG_WRN(("%s no PIDS\n",__FUNCTION__));
4073                if ((result = chm_get_program(p_chm,&p_chm->vch)) != 0)
4074                {
4075                        BDBG_WRN(("chm_get_program failed %d\n",result));
4076
4077                        p_chm->chm_pat_evt.type = eCHM_EVT_STATUS;
4078                        p_chm->chm_pat_evt.id = eCHM_STATUS_NOPAT;
4079                        chm_post_app_event(p_chm,&p_chm->chm_pat_evt);
4080                        return result;
4081                } else
4082                {
4083                        /* need to update the channel map - Alternate Audio pid selection fix */
4084                        ch_map_copy(&(p_chm->ch_map),bapp_cur_ch_map(p_app),0xF);
4085
4086                        if (bapp_task_acquire_mutex(p_chm->ch_map_mutex,45) == b_ok)
4087                        {
4088
4089                                if ((result = chm_update_programs(p_chm,p_chm->freq.idx)) != eCHM_ERR_OK)
4090                                {
4091                                        BDBG_WRN(("chm_update_programs failed %d\n",result));
4092                                }
4093
4094                                bapp_task_release_mutex(p_chm->ch_map_mutex);
4095
4096                                p_chm->chm_pat_evt.type = eCHM_EVT_STATUS;
4097                                p_chm->chm_pat_evt.id = eCHM_STATUS_PAT;
4098                                chm_post_app_event(p_chm,&p_chm->chm_pat_evt);
4099                                bapp_task_sleep(100);
4100                        } else
4101                        {
4102                                BDBG_WRN(("%s:%d failed to acquire channel map mutex\n", __FUNCTION__,__LINE__));
4103                        }
4104
4105                }
4106        } else
4107        {
4108                p_chm->pmt_crc = p_chm->pat_crc = 0;
4109
4110                p_chm->chm_pat_evt.type = eCHM_EVT_STATUS;
4111                p_chm->chm_pat_evt.id = eCHM_STATUS_NOPAT;
4112                chm_post_app_event(p_chm,&p_chm->chm_pat_evt);
4113        }
4114
4115        if (chm_check_cancel(p_chm))
4116        {
4117                BDBG_WRN(("%s cancel detected at line %d\n",__FUNCTION__,__LINE__));
4118                return eCHM_ERR_CANCELED;
4119        }
4120
4121        chm_stream_close(p_chm);
4122
4123        /* Do not start decode if PIDs are all 0.  Doing so can prevent SI filtering from operating correctly. */
4124        if ((p_chm->vch.video_pid != 0) || (p_chm->vch.audio_pid[0] != 0) || (p_chm->vch.pcr_pid != 0))
4125        {
4126                p_app->lang = chm_config_mpeg(p_chm,&p_chm->vch);
4127
4128                if ((result = chm_start_decode(p_chm,force_restart)) != 0)
4129                {
4130                        BDBG_WRN(("chm_start_decode failed\n"));
4131                        return result;
4132                }
4133        }
4134
4135        if (chm_check_cancel(p_chm))
4136        {
4137                BDBG_WRN(("%s cancel detected at line %d\n",__FUNCTION__,__LINE__));
4138                return eCHM_ERR_CANCELED;
4139        }
4140
4141        if (result == 0)
4142        {
4143                /* start decode success so transition to info acquire state */
4144                p_chm->cmd = eCHM_INFO;
4145        }
4146
4147        return result;
4148}
4149
4150/*
4151Summary:
4152Do a tune for the purpose of checking the signal strength.
4153 */
4154int chm_check_signal(chm_mgr_t *p_chm)
4155{
4156        int result = eCHM_ERR_FAILED;
4157        bapp_t *p_app = (bapp_t*)p_chm->p_app;
4158        unsigned int freq_hz;
4159
4160        if (chm_check_cancel(p_chm))
4161                return eCHM_ERR_CANCELED;
4162
4163        if (!ch_map_get_current(bapp_cur_ch_map(p_app),&p_chm->vch,&p_chm->st,&p_chm->freq))
4164        {
4165                BDBG_WRN(("%s ch_map_get_current failed\n",__FUNCTION__));
4166                return eCHM_ERR_FAILED;
4167        }
4168
4169        freq_hz = p_chm->freq.freq_khz * 1000;
4170
4171        if (chm_tune_freq(p_chm,freq_hz,p_chm->freq.idx) != 0)
4172        {
4173                bapp_tune_send_status(p_chm->tune);
4174                BDBG_WRN(("bapp_tune_current_freq failed\n"));
4175                return result;
4176        }
4177
4178        while (!chm_check_cancel(p_chm))
4179        {
4180                bapp_tune_send_status(p_chm->tune);
4181                bapp_task_sleep(50);
4182        }
4183
4184        return result;
4185}
4186
4187#ifdef  HAS_VBI
4188/*
4189Summary:
4190Start SCTE 127 monitoring...
4191 */
4192static int chm_scte127_start(chm_mgr_t *p_chm, uint16_t scte127_pid)
4193{
4194        int cerr = eCHM_ERR_OK;
4195        smessage_stream_params_t params;
4196
4197        BDBG_WRN(("#### SCTE127 0x%x\n", scte127_pid));
4198
4199        if (!p_chm->pscte_127)
4200        {
4201                BDBG_ERR(("%s:%d: SCTE 127 module is not opened",__FILE__, __LINE__));
4202                return eCHM_ERR_FAILED;
4203        }
4204        //chm_scte127_stop(p_chm);
4205
4206        /* clear any pending queue if any */
4207        scte_127_reset(p_chm->pscte_127);
4208        scte_127_enable(p_chm->pscte_127, true);
4209
4210        p_chm->scte127_msg = smessage_open(smessage_format_tsc);
4211        if (NULL == p_chm->scte127_msg)
4212        {
4213                BDBG_ERR(("%s:%d",__FILE__, __LINE__));
4214                cerr = eCHM_ERR_FAILED;
4215                goto ExitFunc;
4216        }
4217        smessage_stream_params_init(&params, p_chm->scte127_msg);
4218        params.band = p_chm->band;
4219        params.pid = scte127_pid;
4220        params.buffer = p_chm->scte127_buf;
4221        params.buffer_size = p_chm->scte127_buf_size;
4222        /* processing is done in callback */
4223        params.data_ready_callback = chm_smessage_scte127_callback;
4224        params.overflow = NULL;
4225        params.callback_context = (void *)p_chm;
4226        params.crc_disabled = true;
4227
4228        if (b_ok != smessage_start(&params, p_chm->scte127_msg))
4229        {
4230                BDBG_ERR(("%s:%d",__FILE__, __LINE__));
4231                cerr = eCHM_ERR_FAILED;
4232        }
4233
4234        ExitFunc:
4235        return cerr;
4236}
4237
4238#endif
4239
4240/*
4241Summary:
4242Start EAS monitoring..
4243 */
4244static int chm_eas_start(chm_mgr_t *p_chm, unsigned short network_pid)
4245{
4246        int cerr = eCHM_ERR_OK;
4247        smessage_stream_params_t params;
4248
4249        chm_eas_stop(p_chm);
4250
4251        p_chm->eas_msg = smessage_open(smessage_format_psi);
4252        if (NULL == p_chm->eas_msg)
4253        {
4254                BDBG_ERR(("%s:%d",__FILE__, __LINE__));
4255                cerr = eCHM_ERR_FAILED;
4256                goto ExitFunc;
4257        }
4258        smessage_stream_params_init(&params, p_chm->eas_msg);
4259        params.band = p_chm->band;
4260        params.pid = 0x1ffb;
4261        params.filter.coef[0] = 0xD8;
4262        params.filter.mask[0] = 0x00;
4263        params.filter.excl[0] = 0xff;
4264        /* All PSIP tables have protocol_version which must be = 0 */
4265        params.filter.coef[8] = 0x00;   /* protocol_version */
4266        params.filter.mask[8] = 0x00;
4267        params.buffer = p_chm->eas_buf;
4268        params.buffer_size = EAS_BUF_LEN;
4269        /* processing is done in callback */
4270        params.data_ready_callback = chm_smessage_eas_callback;
4271        params.overflow = NULL;
4272        params.callback_context = (void *)p_chm;
4273        if (b_ok != smessage_start(&params, p_chm->eas_msg))
4274        {
4275                BDBG_ERR(("%s:%d",__FILE__, __LINE__));
4276                cerr = eCHM_ERR_FAILED;
4277        }
4278        p_chm->eas_timer_started = false;
4279
4280        ExitFunc:
4281        return cerr;
4282}
4283
4284/*
4285Summary:
4286Start CVT monitoring..
4287 */
4288static int chm_cvt_start(chm_mgr_t *p_chm, unsigned short network_pid)
4289{
4290        int cerr = eCHM_ERR_OK;
4291        smessage_stream_params_t params;
4292
4293        BDBG_MSG(("%s:%d (0x%04x)",__FUNCTION__, __LINE__,network_pid));
4294        chm_cvt_stop(p_chm);
4295        p_chm->cvt_msg = smessage_open(smessage_format_psi);
4296        if (NULL == p_chm->cvt_msg)
4297        {
4298                BDBG_ERR(("%s:%d",__FILE__, __LINE__));
4299                cerr = eCHM_ERR_FAILED;
4300                goto ExitFunc;
4301        }
4302        smessage_stream_params_init(&params, p_chm->cvt_msg);
4303        params.band = p_chm->band;
4304        params.pid = (uint16_t)network_pid;
4305        params.filter.coef[0] = 0xD9;
4306        params.filter.mask[0] = 0x00;
4307        params.filter.coef[3] = 0x9f;
4308        params.filter.mask[3] = 0x00;
4309        params.filter.coef[4] = 0x9C;
4310        params.filter.mask[4] = 0x00;
4311#if 0
4312        params.filter.coef[5] = 0x05;
4313        params.filter.mask[5] = 0x00;
4314        params.filter.coef[5] = 0x00;
4315        params.filter.mask[5] = 0x07;   /* APDU 0-5, will let cvt_parse to filter out tables other than 2 and 5 */
4316#endif
4317        params.buffer = p_chm->cvt_buf;
4318        params.buffer_size = CVT_BUF_LEN;
4319        /* processing is done in callback */
4320        params.data_ready_callback = chm_smessage_cvt_callback;
4321        params.overflow = NULL;
4322        params.callback_context = (void *)p_chm;
4323        if (b_ok != smessage_start(&params, p_chm->cvt_msg))
4324        {
4325                BDBG_ERR(("%s:%d",__FILE__, __LINE__));
4326                cerr = eCHM_ERR_FAILED;
4327        }
4328        ExitFunc:
4329        return cerr;
4330}
4331
4332/******************************************************************************
4333 * INPUTS:      context
4334 * OUTPUTS:     none.
4335 * RETURNS:     none
4336 * FUNCTION:    message_callback
4337 * DESCRIPTION: Callback function normally called when a complete message has
4338 *              been received and passed the filter criteria.
4339 ******************************************************************************/
4340
4341void chm_download(chm_mgr_t * p_chm)
4342{
4343        bapp_t *p_app;
4344        unsigned int freq_hz;
4345        vch_t vch;
4346        freq_t freq;
4347        st_t    st;
4348        unsigned short ch_num;
4349        unsigned short PID;
4350        struct image_t * image;
4351        size_t retry;
4352        bresult bres;
4353
4354        p_app = (bapp_t*)p_chm->p_app;
4355
4356        /* disable all message processing during download */
4357        chm_eas_stop(p_chm);
4358        chm_stt_stop(p_chm);
4359        chm_cvt_stop(p_chm);
4360        chm_nit_stop(p_chm);
4361        chm_svct_stop(p_chm);
4362        chm_ntt_stop(p_chm);
4363        chm_emm_stop(p_chm);
4364
4365        ch_map_get_current(bapp_cur_ch_map(p_app), &vch,&st,&freq);
4366        ch_num = vch.ch_num;
4367
4368        PID = 0xFFFF;
4369        freq_hz = (unsigned int)-1;
4370
4371        BDBG_ERR(("#### DSMCC DOWNLOAD ####\n"));
4372
4373        switch (p_chm->cvt.location_type)
4374        {
4375        case 0:
4376                if (!ch_map_set(bapp_cur_ch_map(p_app),p_chm->cvt.source_ID))
4377                {
4378                        BDBG_WRN(("#### CVT Failed to locate download source ID = 0x%04x.#### \n", p_chm->cvt.source_ID));
4379                        break;
4380                } else
4381                {
4382                        if (!ch_map_get_current(&(p_app->settings.ch_map), &vch,&st,&freq))
4383                        {
4384                                BDBG_WRN(("#### CVT Could not get frequency for = 0x%04x #### \n", p_chm->cvt.source_ID));
4385                                break;
4386                        }
4387                        freq_hz = freq.freq_khz * 1000;
4388                }
4389                break;
4390
4391        case 1:
4392                freq_hz = p_chm->cvt.frequency_vector * CHM_VECTOR_MULTIPLIER;
4393                PID = p_chm->cvt.pid;
4394                break;
4395        case 2:
4396                freq_hz = p_chm->cvt.frequency_vector * CHM_VECTOR_MULTIPLIER;
4397                vch.program_num = p_chm->cvt.program_number;
4398                break;
4399        }
4400
4401        if (freq_hz == (unsigned int)-1)
4402                goto failed;
4403
4404
4405        BDBG_WRN(("#### CVT Tune %d #### \n", freq.freq_khz * 1000));
4406        if (chm_tune_freq(p_chm,freq_hz,freq.idx) != eCHM_ERR_OK)
4407                goto failed;
4408
4409
4410        if (PID == 0xFFFF)
4411        {
4412                if (chm_get_program_pid(p_chm,p_chm->band, vch.program_num,&PID ) != eCHM_ERR_OK)
4413                {
4414                        BDBG_WRN(("#### CVT Could not find program %d for source_ID 0x%04x, freq = %d\n", vch.program_num,p_chm->cvt.source_ID,freq_hz));
4415                        goto failed;
4416                }
4417        }
4418
4419        if (image_init() != b_ok)
4420        {
4421                BDBG_WRN(("#### CVT Download Init Failed #### \n"));
4422                goto failed;
4423        }
4424
4425        retry = 3;
4426        while (0 != retry)
4427        {
4428                if ( image_receive(p_chm->band,PID,&image, p_chm->cvt.code_file_name_length, &(p_chm->cvt.code_file_name[0])) == b_ok)
4429                {
4430                        break;
4431                }
4432                BDBG_WRN(("#### CVT Download Failed #### \n"));
4433                --retry;
4434        }
4435        if (0 == retry)
4436        {
4437                goto failed;
4438        }
4439        chm_stop_decode(p_chm);
4440        bres = chm_write_software(image);
4441        if (b_ok != bres)
4442        {
4443                goto failed;
4444        }
4445
4446        /* restore channel number to previous video channel */
4447        ch_map_set_ch(bapp_cur_ch_map(p_app),ch_num);
4448
4449        p_app->settings_dirty = true;
4450        bapp_save_settings(p_app);
4451
4452        chip_reset();
4453
4454        failed:
4455        p_chm->cmd = eCHM_TUNE;
4456        ch_map_set_ch(bapp_cur_ch_map(p_app),ch_num);
4457}
4458
4459/*
4460Summary:
4461Steady state loop..
4462 */
4463int chm_start_scte65(chm_mgr_t *p_chm,unsigned short network_pid)
4464{
4465        bapp_t *p_app = (bapp_t*)p_chm->p_app;
4466
4467        chm_emm_start(p_chm,p_app->settings.EMM_PID);
4468
4469        if (!p_app->settings.psi_scan)
4470        {
4471                ch_map_reset(&(p_chm->ch_map));
4472                chm_stt_start(p_chm,network_pid);
4473                chm_cvt_start(p_chm,network_pid);
4474                chm_nit_start(p_chm, network_pid);
4475                chm_svct_start(p_chm, network_pid);
4476                chm_ntt_start(p_chm, network_pid);
4477        }
4478        return eCHM_PROG_IDLE;
4479}
4480
4481#define CHECK_PROGRAM
4482#ifdef CHECK_PROGRAM
4483/*
4484Summary:
4485check the program for changes..
4486 */
4487int chm_check_program(chm_mgr_t *p_chm)
4488{
4489        int result = eCHM_PROG_IDLE;
4490        bapp_t *p_app = (bapp_t*)p_chm->p_app;
4491        vch_t   *vch;
4492        unsigned int pmt_crc,pat_crc;
4493        bool restart = false;
4494
4495        pmt_crc = p_chm->pmt_crc;
4496        pat_crc = p_chm->pat_crc;
4497        /* temporary until we do smart PAT */
4498        vch = &p_chm->vch;
4499        BDBG_MSG(("***** chm_get_program *****\n"));
4500
4501        if ((result = chm_get_program(p_chm,vch)) != 0)
4502        {
4503                BDBG_WRN(("chm_get_program failed %d\n",result));
4504                return eCHM_PROG_IDLE; /* return state expected */
4505        } else
4506        {
4507                if (p_chm->network_pid != p_app->settings.network_PID)
4508                {
4509                        /* Send message to app */
4510                        p_chm->chm_network_evt.type = eCHM_EVT_NETWORK;
4511                        p_chm->chm_network_evt.id = p_chm->network_pid;
4512                        chm_post_app_event(p_chm,&p_chm->chm_network_evt);
4513                        result = eCHM_PROG_SCTE65;
4514                }
4515
4516                /* Check the PIDs match vcm PIDs */
4517                if ((pat_crc != p_chm->pat_crc) || (pmt_crc != p_chm->pmt_crc))
4518                {
4519                        if (vch->pcr_pid != p_chm->vch.pcr_pid)
4520                        {
4521                                BDBG_WRN(("VCM PCR PIDs do not match(0x%04x != 0x%04x)\n",vch->pcr_pid, p_chm->vch.pcr_pid));
4522                                p_chm->vch.pcr_pid = vch->pcr_pid;
4523                                restart = true;
4524                        }
4525                        if (vch->video_pid != p_chm->vch.video_pid)
4526                        {
4527                                BDBG_WRN(("VCM Video PIDs do not match(0x%04x != 0x%04x)\n",vch->video_pid, p_chm->vch.video_pid));
4528                                p_chm->vch.video_pid = vch->video_pid;
4529                                restart = true;
4530                        }
4531                        if ((vch->num_audio < p_chm->vch.cur_audio) || (p_chm->vch.audio_pid[p_chm->vch.cur_audio] != vch->audio_pid[p_chm->vch.cur_audio]))
4532                        {
4533                                /*Fixed error where cur_audio was set to num_audio. */
4534                                if (p_chm->vch.cur_audio >= vch->num_audio)
4535                                        p_chm->vch.cur_audio = 0;
4536                                BDBG_WRN(("VCM Audio PID no longer valid(0x%04x != 0x%04x)\n", vch->audio_pid[p_chm->vch.cur_audio],p_chm->vch.audio_pid[p_chm->vch.cur_audio]));
4537                                bapp_util_memcpy(p_chm->vch.audio_pid,vch->audio_pid,sizeof(unsigned short) * MAX_AUDIO_PIDS);
4538                                bapp_util_memcpy(p_chm->vch.audio_type,vch->audio_type,sizeof(unsigned char) * MAX_AUDIO_PIDS);
4539                                bapp_util_memcpy(p_chm->vch.audio_lang,vch->audio_lang,sizeof(char) * MAX_AUDIO_PIDS * 3);
4540                                restart = true;
4541                        }
4542
4543                        if (restart)
4544                        {
4545                                chm_stop_decode(p_chm);
4546
4547                                p_app->lang = chm_config_mpeg(p_chm,&p_chm->vch);
4548
4549                                if ((result = chm_start_decode(p_chm,true)) != 0)
4550                                {
4551                                        BDBG_WRN(("%s chm_start_decode failed\n",__FUNCTION__));
4552                                }
4553                        }
4554                } else
4555                {
4556                        BDBG_MSG(("####pat_crc or pmt_crc not match####\n"));
4557                }
4558        }
4559        return eCHM_PROG_IDLE;
4560}
4561#endif
4562/*
4563Summary:
4564Steady state loop..
4565 */
4566int chm_info(chm_mgr_t *p_chm)
4567{
4568        bapp_t *p_app = (bapp_t*)p_chm->p_app;
4569        p_chm->network_pid = p_app->settings.network_PID;
4570
4571        while (!chm_check_cancel(p_chm))
4572        {
4573                chm_state_t curstate = p_chm->state;
4574                switch (curstate)
4575                {
4576                case eCHM_PROG_INIT:
4577                        chm_eas_start(p_chm, 0x1FFB);
4578                        p_chm->state = eCHM_PROG_CAT;
4579                        break;
4580                case eCHM_PROG_CAT:
4581                        chm_cat_start(p_chm);
4582                        if (p_chm->network_pid != 0)
4583                                p_chm->state = eCHM_PROG_SCTE65;
4584                        else
4585                                p_chm->state = eCHM_PROG_IDLE;
4586
4587                        break;
4588                case eCHM_PROG_SCTE65:
4589                        p_chm->state = chm_start_scte65(p_chm,p_chm->network_pid);
4590                        break;
4591                case eCHM_PROG_IDLE:
4592                        {
4593                                static unsigned int last_signal_check = 0;
4594                                static unsigned int last_chmap_check = 0;
4595#ifdef CHECK_PROGRAM
4596                                static unsigned int last_prog_check = 0;
4597
4598                                if (last_prog_check < bapp_task_getticks())
4599                                {
4600                                        p_chm->state = chm_check_program(p_chm);
4601#ifdef  HAS_VBI
4602
4603                                        /* with latest changes, the scte127_pid could be 0 when in eCHM_PROG_INIT state, so check here again */
4604                                        if (p_chm->pscte_127 && p_chm->vch.scte127_pid && !p_chm->scte127_msg)
4605                                        {
4606                                                BDBG_WRN(("Start SCTE 127 packet checking..."));
4607                                                chm_scte127_start(p_chm, p_chm->vch.scte127_pid);
4608                                        }
4609#endif
4610                                        last_prog_check = bapp_task_getticks() + MS_TO_TICKS(CHM_CHECK_PROG_FREQ);
4611                                }
4612#endif
4613                                if (last_signal_check < bapp_task_getticks())
4614                                {
4615                                        chm_send_status(p_chm,0,true);
4616                                        last_signal_check = bapp_task_getticks() + MS_TO_TICKS(CHM_CHECK_SIGNAL_FREQ);
4617                                }
4618
4619                                if (last_signal_check < bapp_task_getticks())
4620                                {
4621                                        chm_send_status(p_chm,0,true);
4622                                        last_signal_check = bapp_task_getticks() + MS_TO_TICKS(CHM_CHECK_SIGNAL_FREQ);
4623                                }
4624
4625                                p_chm->chmap_evt.ticks = 0;
4626                                p_chm->chmap_evt.type = eCHM_EVT_STATUS;
4627                                p_chm->chmap_evt.id = eCHM_STATUS_CHMAP;
4628                                /* Compare the NIT - MMS to the current one */
4629                                if (p_chm->mms_changed)
4630                                {
4631                                        if (ch_map_cmp_mms(&(p_chm->ch_map.mms_map),&(p_app->settings.ch_map.mms_map)) != 0)
4632                                                p_chm->chmap_evt.ticks |= 0x8;
4633                                }
4634
4635                                /* Compare the NIT - CDS to the current one */
4636                                if (p_chm->cds_changed)
4637                                {
4638                                        if (ch_map_cmp_freq(&(p_chm->ch_map.freq_map),&(p_app->settings.ch_map.freq_map)) != 0)
4639                                                p_chm->chmap_evt.ticks |= 0x1;
4640                                }
4641
4642                                /* Compare the NTT to the current one */
4643                                if (p_chm->sns_changed)
4644                                {
4645                                        if (ch_map_cmp_st(&(p_chm->ch_map.st_map),&(p_app->settings.ch_map.st_map)) != 0)
4646                                                p_chm->chmap_evt.ticks |= 0x4;
4647                                }
4648
4649                                /* Compare the SVCT to the current one */
4650                                if (p_chm->vcm_changed)
4651                                {
4652                                        if (bapp_task_acquire_mutex(p_chm->ch_map_mutex,45) == b_ok)
4653                                        {
4654                                                if (chm_update_programs(p_chm,p_chm->freq.idx) != eCHM_ERR_OK)
4655                                                {
4656                                                        BDBG_WRN(("chm_update_programs failed %s\n",__FUNCTION__));
4657                                                }
4658
4659                                                bapp_task_release_mutex(p_chm->ch_map_mutex);
4660                                        } else
4661                                        {
4662                                                BDBG_WRN(("%s:%d failed to acquire channel map mutex\n", __FUNCTION__,__LINE__));
4663                                        }
4664
4665                                        if (ch_map_cmp_vch(&(p_chm->ch_map.vch_map),&(p_app->settings.ch_map.vch_map)) != 0)
4666                                                p_chm->chmap_evt.ticks |= 0x2;
4667                                }
4668
4669                                if (p_chm->chmap_evt.ticks)
4670                                {
4671                                        /* copy channel map so application can perform update without risk of modification by channel manager */
4672                                        chm_post_app_event(p_chm,&p_chm->chmap_evt);
4673                                        p_chm->state = eCHM_PROG_UPDATING;
4674                                        /* p_chm->xxx_changed flags will be reset when filters are restarted */
4675                                }
4676
4677                        }
4678                        break;
4679
4680                        /* Give application time to update channel map before searching for SCTE65 again */
4681                case eCHM_PROG_UPDATING:
4682                        {
4683                                static unsigned int updating_check = 0;
4684
4685                                if (updating_check < bapp_task_getticks())
4686                                {
4687                                        if (updating_check == 0)
4688                                        {
4689                                                updating_check = bapp_task_getticks() + MS_TO_TICKS(CHM_UPDATING_DELAY);
4690                                        } else
4691                                        {
4692                                                updating_check = 0;
4693                                                p_chm->state = eCHM_PROG_SCTE65;
4694                                        }
4695                                }
4696                                break;
4697                        }
4698
4699
4700                }
4701                bapp_task_sleep(CHM_IDLE_TIMEOUT);
4702                if (p_chm->state == curstate)
4703                {
4704                        BDBG_MSG(("p_chm->state is still %d\n",p_chm->state));
4705                } else
4706                {
4707                        BDBG_WRN(("chm state changed from %d to %d\n",curstate,p_chm->state));
4708                }
4709
4710        }
4711
4712        return eCHM_ERR_OK;
4713}
4714
4715/*
4716Summary:
4717Channel Manager Task.
4718 */
4719static void chm_handler(void *data)
4720{
4721        chm_cmd_t orig_cmd;
4722        chm_mgr_t *p_chm = (chm_mgr_t *)data;
4723        chm_cmd_event_t *p_cmd;
4724
4725        while (1)
4726        {
4727                orig_cmd = p_chm->cmd;
4728                switch (p_chm->cmd)
4729                {
4730                case eCHM_CANCEL:
4731                        p_cmd = (chm_cmd_event_t*)bapp_task_pend_event(p_chm->queue,-1);
4732                        if (p_cmd == NULL)
4733                                break;
4734
4735                        p_chm->cmd = (chm_cmd_t)p_cmd->cmd_id;
4736                        break;
4737                case eCHM_SAP:
4738                        p_chm->cmd = eCHM_CANCEL;
4739                        break;
4740
4741                case eCHM_STOP:
4742                        chm_stop_decode(p_chm);
4743                        p_chm->cmd = eCHM_CANCEL;
4744                        break;
4745
4746                case eCHM_TUNE:
4747                        chm_tune(p_chm); 
4748                        break;
4749                case eCHM_HUNT:
4750                        p_chm->hunt_cnt = 0;
4751                        p_chm->cmd = eCHM_HUNTING;
4752                        break;
4753                case eCHM_HUNTING:
4754                        chm_hunt(p_chm);
4755                        break;
4756                case eCHM_PENDING_INIT:
4757                        chm_pending_init(p_chm); 
4758                        break;
4759                case eCHM_INFO:
4760                        p_chm->state = eCHM_PROG_INIT;
4761                        chm_info(p_chm);
4762                        break;
4763                case eCHM_CHECK_SIGNAL:
4764                        chm_check_signal(p_chm);
4765                        break;
4766                case eCHM_DOWNLOAD:
4767                        chm_download(p_chm);
4768                        break;
4769                }
4770
4771                if (orig_cmd != p_chm->cmd)
4772                {
4773                        BDBG_WRN(("CHM CMD changed from %s to %s\n", s_chm_cmd_name[orig_cmd],s_chm_cmd_name[p_chm->cmd]));
4774                }
4775
4776                /* Yield a little */
4777                bapp_task_sleep(10);
4778        }
4779}
4780
4781/*
4782Summary:
4783Initialize the channel manager.
4784 */
4785
4786void chm_init(chm_mgr_t *p_chm, void *v_app)
4787{
4788        bapp_task_params   params;
4789        bresult rc;
4790        bapp_t *p_app = (bapp_t*)v_app;
4791        bapp_util_memset(p_chm,0,sizeof(chm_mgr_t));
4792
4793        p_chm->fe_type = eFREQ_TABLE_NORTH_AMERICA_QAM;
4794        p_chm->p_app = v_app;
4795        p_chm->tune = p_app->nexus.tune;
4796        rc = bapp_task_create_queue(&p_chm->queue,p_chm->event,MAX_CHM_EVENT);
4797        BDBG_ASSERT(rc == b_ok);
4798        rc = bapp_task_create_queue(&p_chm->gen_queue,p_chm->gen_event,MAX_MSG_EVENTS);
4799        BDBG_ASSERT(rc == b_ok);
4800        rc = bapp_task_create_mutex(&p_chm->mutex);
4801        BDBG_ASSERT(rc == b_ok);
4802        rc = bapp_task_create_mutex(&p_chm->ch_map_mutex);
4803        BDBG_ASSERT(rc == b_ok);
4804        ch_map_init(&(p_chm->ch_map),p_chm->ch_map_mutex);
4805
4806        p_chm->stack = bapp_util_malloc(CHM_INT_STK_SIZE * 4);
4807        BDBG_ASSERT(p_chm->stack);
4808
4809        params.priority = CHM_INT_PRIORITY;
4810        params.stack = p_chm->stack;
4811        params.name = "chan_mgr";
4812        params.stack_size = CHM_INT_STK_SIZE;
4813
4814        p_chm->svct_buf = bapp_util_malloc(SVCT_BUF_LEN);
4815        p_chm->pat_buf = bapp_util_malloc(PAT_BUF_LEN);
4816        p_chm->cat_buf = bapp_util_malloc(CAT_BUF_LEN);
4817        p_chm->pmt_buf = bapp_util_malloc(PMT_BUF_LEN);
4818        p_chm->stt_buf = bapp_util_malloc(STT_BUF_LEN);
4819        p_chm->nit_buf = bapp_util_malloc(NIT_BUF_LEN);
4820        p_chm->ntt_buf = bapp_util_malloc(NTT_BUF_LEN);
4821        p_chm->eas_buf = bapp_util_malloc(EAS_BUF_LEN);
4822        p_chm->cvt_buf = bapp_util_malloc(EAS_BUF_LEN);
4823        p_chm->emm_buf = bapp_util_malloc(EMM_BUF_LEN);
4824
4825        BDBG_ASSERT(p_chm->svct_buf && p_chm->pat_buf && p_chm->pmt_buf && 
4826                                p_chm->stt_buf && p_chm->nit_buf && p_chm->ntt_buf && p_chm->cat_buf);
4827
4828        p_chm->vcm_cb.data = p_chm;
4829        p_chm->vcm_cb.cb = chm_vcm_cb;
4830
4831        p_chm->sns_cb.data = p_chm;
4832        p_chm->sns_cb.cb = chm_sns_cb;
4833
4834        p_chm->cds_cb.data = p_chm;
4835        p_chm->cds_cb.cb = chm_cds_cb;
4836
4837        p_chm->mms_cb.data = p_chm;
4838        p_chm->mms_cb.cb = chm_mms_cb;
4839
4840        SI_SVCT_Init (&p_chm->vcm_cb,0xFF);
4841
4842        SI_NTT_Init (&p_chm->sns_cb,0xFF);
4843
4844        SI_NIT_Init (&p_chm->cds_cb,&p_chm->mms_cb,0xFF,0xFF);
4845
4846        SI_STT_Init ();
4847
4848#ifdef  HAS_VBI
4849        p_chm->pscte_127 = scte_127_init();
4850        BDBG_ASSERT(p_chm->pscte_127);
4851        s_pscte_127 = p_chm->pscte_127;
4852        p_chm->scte127_buf_size = 188 * 1;      /* currently 1 packet */
4853        p_chm->scte127_buf = bapp_util_malloc(p_chm->scte127_buf_size);
4854        BDBG_ASSERT(p_chm->scte127_buf);
4855#endif
4856
4857        bstream_mpeg_init(&p_chm->mpeg[CURR_CH]);
4858        bstream_mpeg_init(&p_chm->mpeg[NEXT_CH]);
4859        bstream_mpeg_init(&p_chm->mpeg[PREV_CH]);
4860
4861        p_chm->smsg = smessage_open(smessage_format_psi);
4862
4863        BDBG_ASSERT(p_chm->smsg);
4864
4865        p_chm->vendor_id = DEF_VENDOR_ID;
4866        p_chm->hardware_version_id = DEF_HARDWARE_ID;
4867        p_chm->cvt_valid = false;
4868
4869#if defined(ENABLE_UMESSAGE)
4870        cmode_init();
4871#endif
4872
4873        bapp_av_open(&p_chm->av, &p_app->nexus);
4874        BDBG_ASSERT(p_chm->av);
4875
4876        bapp_task_start_task(&p_chm->task,&params,chm_handler,p_chm);
4877
4878#ifdef BDBG_DEBUG_BUILD
4879        BDBG_SetModuleLevel("chan_mgr",BDBG_eWrn);
4880#endif
4881}
4882
4883/*
4884Summary:
4885Function to pass a command to the channel manager.
4886Any results and notification is handled by passing events to the app via
4887the msg_queue.
4888
4889 */
4890void chm_cmd(chm_mgr_t *p_chm,chm_cmd_event_t *p_cmd_evt)
4891{
4892        chm_cmd_t       cmd;
4893
4894        BDBG_ASSERT(p_chm);
4895        BDBG_ASSERT(p_cmd_evt);
4896
4897        cmd = p_cmd_evt->cmd_id;
4898
4899        /* Handle special case to rotate audio */
4900        if ((cmd == eCHM_SAP) && (p_chm->cmd != eCHM_CANCEL))
4901        {
4902                BDBG_WRN(("Command %s, during %s\n",s_chm_cmd_name[cmd], s_chm_cmd_name[p_chm->cmd]));
4903                bapp_task_post_event(p_chm->queue,(bapp_task_event_t)p_cmd_evt);
4904                return;
4905        }
4906        if ((cmd != eCHM_CANCEL) && (p_chm->cmd != eCHM_CANCEL))
4907        {
4908                BDBG_WRN(("Canceling pervious command %s for %s\n", s_chm_cmd_name[p_chm->cmd],s_chm_cmd_name[cmd]));
4909                p_chm->cancel_cmd.cmd_id = eCHM_CANCEL;
4910                bapp_task_post_event(p_chm->queue,(bapp_task_event_t)&p_chm->cancel_cmd);
4911                bapp_task_sleep(40); /* yield so thread can process event right away */
4912        }
4913
4914        bapp_task_post_event(p_chm->queue,(bapp_task_event_t)p_cmd_evt);
4915        bapp_task_sleep(10); /* yield so thread can process event right away */
4916}
4917
4918bresult chm_write_software(struct image_t * image)
4919{
4920        return image_write(image);
4921}
4922
4923#define CHM_SC_MASK 0xc0
4924#define CHM_SC_BUFFER_SIZE (188*10)
4925static unsigned char chm_sc_buffer[CHM_SC_BUFFER_SIZE];
4926
4927static void * chm_sc_callback(void * c, size_t msg_size)
4928{
4929        unsigned int * pdata_ready = (unsigned int *)c;
4930        *pdata_ready = msg_size;
4931        return NULL;
4932}
4933
4934bool chm_check_sc(chm_mgr_t *p_chm, bband_t band, unsigned short pid)
4935{
4936        smessage_stream_t ms;
4937        smessage_stream_params_t params;
4938        bresult bres;
4939        bool result;
4940        unsigned int count;
4941        volatile unsigned int data_ready;
4942        unsigned char * walker;
4943
4944        result = false;
4945        ms = smessage_open(smessage_format_tsc);
4946        if (NULL == ms)
4947        {
4948                BDBG_ERR(("%s : smessage_open failed", __PRETTY_FUNCTION__));
4949                goto ExitFunc;
4950        }
4951        smessage_stream_params_init(&params, ms);
4952        params.band = band;
4953        params.pid = pid;
4954        params.buffer_size = CHM_SC_BUFFER_SIZE;
4955        params.buffer = chm_sc_buffer;
4956        params.data_ready_callback = chm_sc_callback;
4957        params.overflow = chm_sc_callback;
4958        params.callback_context = (void *)&data_ready;
4959        data_ready = 0;
4960        bres = smessage_start(&params, ms);
4961        if (b_ok != bres)
4962        {
4963                smessage_close(ms);
4964                BDBG_ERR(("%s : smessage_start", __PRETTY_FUNCTION__));
4965                goto ExitFunc;
4966        }
4967        /* Updating unsigned int is atomic operation on mips. We can just wait for
4968           callback to update our flag when data is ready */
4969        count = 3;
4970        do
4971        {
4972                bapp_task_sleep(50);
4973                count--;
4974        }while ((0 == data_ready)&&(0 != count));
4975
4976        bres = smessage_stop(ms);
4977        if (b_ok != bres)
4978        {
4979                smessage_close(ms);
4980                BDBG_ERR(("%s : smessage_stop", __PRETTY_FUNCTION__));
4981                goto ExitFunc;
4982        }
4983        smessage_close(ms);
4984        /* Figure out if we got data and if sc flags are set */
4985        if (0 != data_ready)
4986        {
4987                /* We have data. Check few packets for sc bits */
4988                walker = chm_sc_buffer;
4989                for (count = 0; count < 5; count++)
4990                {
4991                        if (0 != (walker[3] & CHM_SC_MASK))
4992                        {
4993                                goto ExitFunc;
4994                        }
4995                        walker += 188;
4996                }
4997                result = true;
4998        }
4999        ExitFunc:
5000        BDBG_ERR(("pid %d %s", pid, (result == true ? "clear" : "encr")));
5001        return result;
5002}
5003
Note: See TracBrowser for help on using the repository browser.