Merge "libdvr: Request to support "appending recording" [1/1]" into r-tv-dev
diff --git a/Android.bp b/Android.bp
index 656cce3..c0f9e6b 100644
--- a/Android.bp
+++ b/Android.bp
@@ -9,14 +9,14 @@
 cc_library_shared {
     name: "libamdvr",
     vendor: true,
-    compile_multilib: "32",
+    compile_multilib: "both",
 
     arch: {
         arm: {
             instruction_set: "arm",
         },
         arm64: {
-            enabled: false,
+            enabled: true,
         },
         x86: {
             enabled: false,
@@ -40,6 +40,7 @@
         "src/segment.c",
         "src/am_crypt.c",
         "src/des.c",
+        "src/dvr_mutex.c",
     ],
     shared_libs: [
         "libcutils",
@@ -74,7 +75,7 @@
 
 cc_library_shared {
     name: "libamdvr.system",
-    compile_multilib: "32",
+    compile_multilib: "both",
     system_ext_specific: true,
 
     arch: {
@@ -82,7 +83,7 @@
             instruction_set: "arm",
         },
         arm64: {
-            enabled: false,
+            enabled: true,
         },
         x86: {
             enabled: false,
@@ -106,6 +107,7 @@
         "src/segment.c",
         "src/am_crypt.c",
         "src/des.c",
+        "src/dvr_mutex.c",
     ],
     shared_libs: [
         "libcutils",
diff --git a/Makefile b/Makefile
index 74ec626..ff4a5af 100644
--- a/Makefile
+++ b/Makefile
@@ -17,6 +17,7 @@
 	src/list_file.c\
 	src/segment.c\
 	src/am_crypt.c\
+	src/dvr_mutex.c\
 	src/des.c
 LIBAMDVR_OBJS := $(patsubst %.c,%.o,$(LIBAMDVR_SRCS))
 
diff --git a/include/am_crypt.h b/include/am_crypt.h
index db67008..91494d8 100644
--- a/include/am_crypt.h
+++ b/include/am_crypt.h
@@ -22,7 +22,7 @@
 int am_crypt_des_close(void *cryptor);
 
 int am_crypt_des_crypt(void* cryptor, uint8_t* dst,
-		       const uint8_t *src, uint32_t *len, int decrypt);
+               const uint8_t *src, int *len, int decrypt);
 
 #ifdef __cplusplus
 }
diff --git a/include/amci.h b/include/amci.h
new file mode 100644
index 0000000..cf7ceab
--- /dev/null
+++ b/include/amci.h
@@ -0,0 +1,35 @@
+/* SPDX-License-Identifier: (GPL-2.0+ OR MIT) */
+/*
+ * Copyright (c) 2019 Amlogic, Inc. All rights reserved.
+ */
+
+#ifndef _AMCI_H
+#define _AMCI_H
+
+/* #include <asm/types.h> */
+#include <linux/types.h>
+
+
+enum AM_CI_IO_MODE {
+    AM_CI_IOR = 0,
+    AM_CI_IOW,
+    AM_CI_MEMR,
+    AM_CI_MEMW
+};
+
+struct ci_rw_param {
+    enum AM_CI_IO_MODE mode;
+    int addr;
+    u_int8_t value;
+};
+
+
+#define AMCI_IOC_MAGIC  'D'
+
+#define AMCI_IOC_RESET       _IO(AMCI_IOC_MAGIC, 0x00)
+#define AMCI_IOC_IO          _IOWR(AMCI_IOC_MAGIC, 0x01, struct ci_rw_param)
+#define AMCI_IOC_GET_DETECT  _IOWR(AMCI_IOC_MAGIC, 0x02, int)
+#define AMCI_IOC_SET_POWER   _IOW(AMCI_IOC_MAGIC, 0x03, int)
+
+
+#endif
\ No newline at end of file
diff --git a/include/des.h b/include/des.h
index 3ab4c8e..5bba03b 100644
--- a/include/des.h
+++ b/include/des.h
@@ -24,12 +24,6 @@
 

 #include <stdint.h>

 

-/**

- * @defgroup lavu_des DES

- * @ingroup lavu_crypto

- * @{

- */

-

 typedef struct AVDES {

     uint64_t round_keys[3][16];

     int triple_des;

diff --git a/include/dmx.h b/include/dmx.h
index bb68939..329694f 100644
--- a/include/dmx.h
+++ b/include/dmx.h
@@ -35,51 +35,51 @@
 
 enum dmx_output
 {
-	DMX_OUT_DECODER, /* Streaming directly to decoder. */
-	DMX_OUT_TAP,     /* Output going to a memory buffer */
-			 /* (to be retrieved via the read command).*/
-	DMX_OUT_TS_TAP,  /* Output multiplexed into a new TS  */
-			 /* (to be retrieved by reading from the */
-			 /* logical DVR device).                 */
-	DMX_OUT_TSDEMUX_TAP /* Like TS_TAP but retrieved from the DMX device */
+    DMX_OUT_DECODER, /* Streaming directly to decoder. */
+    DMX_OUT_TAP,     /* Output going to a memory buffer */
+             /* (to be retrieved via the read command).*/
+    DMX_OUT_TS_TAP,  /* Output multiplexed into a new TS  */
+             /* (to be retrieved by reading from the */
+             /* logical DVR device).                 */
+    DMX_OUT_TSDEMUX_TAP /* Like TS_TAP but retrieved from the DMX device */
 };
 
 typedef enum dmx_output dmx_output_t;
 
 typedef enum dmx_input
 {
-	DMX_IN_FRONTEND, /* Input from a front-end device.  */
-	DMX_IN_DVR       /* Input from the logical DVR device.  */
+    DMX_IN_FRONTEND, /* Input from a front-end device.  */
+    DMX_IN_DVR       /* Input from the logical DVR device.  */
 } dmx_input_t;
 
 
 typedef enum dmx_ts_pes
 {
-	DMX_PES_AUDIO0,
-	DMX_PES_VIDEO0,
-	DMX_PES_TELETEXT0,
-	DMX_PES_SUBTITLE0,
-	DMX_PES_PCR0,
+    DMX_PES_AUDIO0,
+    DMX_PES_VIDEO0,
+    DMX_PES_TELETEXT0,
+    DMX_PES_SUBTITLE0,
+    DMX_PES_PCR0,
 
-	DMX_PES_AUDIO1,
-	DMX_PES_VIDEO1,
-	DMX_PES_TELETEXT1,
-	DMX_PES_SUBTITLE1,
-	DMX_PES_PCR1,
+    DMX_PES_AUDIO1,
+    DMX_PES_VIDEO1,
+    DMX_PES_TELETEXT1,
+    DMX_PES_SUBTITLE1,
+    DMX_PES_PCR1,
 
-	DMX_PES_AUDIO2,
-	DMX_PES_VIDEO2,
-	DMX_PES_TELETEXT2,
-	DMX_PES_SUBTITLE2,
-	DMX_PES_PCR2,
+    DMX_PES_AUDIO2,
+    DMX_PES_VIDEO2,
+    DMX_PES_TELETEXT2,
+    DMX_PES_SUBTITLE2,
+    DMX_PES_PCR2,
 
-	DMX_PES_AUDIO3,
-	DMX_PES_VIDEO3,
-	DMX_PES_TELETEXT3,
-	DMX_PES_SUBTITLE3,
-	DMX_PES_PCR3,
+    DMX_PES_AUDIO3,
+    DMX_PES_VIDEO3,
+    DMX_PES_TELETEXT3,
+    DMX_PES_SUBTITLE3,
+    DMX_PES_PCR3,
 
-	DMX_PES_OTHER
+    DMX_PES_OTHER
 } dmx_pes_type_t;
 
 #define DMX_PES_AUDIO    DMX_PES_AUDIO0
@@ -91,18 +91,18 @@
 
 typedef struct dmx_filter
 {
-	__u8  filter[DMX_FILTER_SIZE];
-	__u8  mask[DMX_FILTER_SIZE];
-	__u8  mode[DMX_FILTER_SIZE];
+    __u8  filter[DMX_FILTER_SIZE];
+    __u8  mask[DMX_FILTER_SIZE];
+    __u8  mode[DMX_FILTER_SIZE];
 } dmx_filter_t;
 
 
 struct dmx_sct_filter_params
 {
-	__u16          pid;
-	dmx_filter_t   filter;
-	__u32          timeout;
-	__u32          flags;
+    __u16          pid;
+    dmx_filter_t   filter;
+    __u32          timeout;
+    __u32          flags;
 #define DMX_CHECK_CRC       1
 #define DMX_ONESHOT         2
 #define DMX_IMMEDIATE_START 4
@@ -120,96 +120,96 @@
 #ifdef CONFIG_AMLOGIC_DVB_COMPAT
 
 enum dmx_input_source {
-	INPUT_DEMOD,
-	INPUT_LOCAL,
-	INPUT_LOCAL_SEC
+    INPUT_DEMOD,
+    INPUT_LOCAL,
+    INPUT_LOCAL_SEC
 };
 
 /**
  * struct dmx_non_sec_es_header - non-sec Elementary Stream (ES) Header
  *
  * @pts_dts_flag:[1:0], 01:pts valid, 10:dts valid
- * @pts:	pts value
- * @dts:	dts value
- * @len:	data len
+ * @pts:    pts value
+ * @dts:    dts value
+ * @len:    data len
  */
 struct dmx_non_sec_es_header {
-	__u8 pts_dts_flag;
-	__u64 pts;
-	__u64 dts;
-	__u32 len;
+    __u8 pts_dts_flag;
+    __u64 pts;
+    __u64 dts;
+    __u32 len;
 };
 
 /**
  * struct dmx_sec_es_data - sec Elementary Stream (ES)
  *
  * @pts_dts_flag:[1:0], 01:pts valid, 10:dts valid
- * @pts:	pts value
- * @dts:	dts value
- * @buf_start:	buf start addr
- * @buf_end:	buf end addr
+ * @pts:    pts value
+ * @dts:    dts value
+ * @buf_start:    buf start addr
+ * @buf_end:    buf end addr
  * @data_start: data start addr
  * @data_end: data end addr
  */
 struct dmx_sec_es_data {
-	__u8 pts_dts_flag;
-	__u64 pts;
-	__u64 dts;
-	__u32 buf_start;
-	__u32 buf_end;
-	__u32 data_start;
-	__u32 data_end;
+    __u8 pts_dts_flag;
+    __u64 pts;
+    __u64 dts;
+    __u32 buf_start;
+    __u32 buf_end;
+    __u32 data_start;
+    __u32 data_end;
 };
 
 struct dmx_sec_ts_data {
-	__u32 buf_start;
-	__u32 buf_end;
-	__u32 data_start;
-	__u32 data_end;
+    __u32 buf_start;
+    __u32 buf_end;
+    __u32 data_start;
+    __u32 data_end;
 };
 
 enum dmx_audio_format {
-	AUDIO_UNKNOWN = 0,	/* unknown media */
-	AUDIO_MPX = 1,		/* mpeg audio MP2/MP3 */
-	AUDIO_AC3 = 2,		/* Dolby AC3/EAC3 */
-	AUDIO_AAC_ADTS = 3,	/* AAC-ADTS */
-	AUDIO_AAC_LOAS = 4,	/* AAC-LOAS */
-	AUDIO_DTS = 5,		/* DTS */
-	AUDIO_MAX
+    AUDIO_UNKNOWN = 0,    /* unknown media */
+    AUDIO_MPX = 1,        /* mpeg audio MP2/MP3 */
+    AUDIO_AC3 = 2,        /* Dolby AC3/EAC3 */
+    AUDIO_AAC_ADTS = 3,    /* AAC-ADTS */
+    AUDIO_AAC_LOAS = 4,    /* AAC-LOAS */
+    AUDIO_DTS = 5,        /* DTS */
+    AUDIO_MAX
 };
 
 struct dmx_mem_info {
-	__u32 dmx_total_size;
-	__u32 dmx_buf_phy_start;
-	__u32 dmx_free_size;
-	__u32 dvb_core_total_size;
-	__u32 dvb_core_free_size;
-	__u32 wp_offset;
-	__u64 newest_pts;
+    __u32 dmx_total_size;
+    __u32 dmx_buf_phy_start;
+    __u32 dmx_free_size;
+    __u32 dvb_core_total_size;
+    __u32 dvb_core_free_size;
+    __u32 wp_offset;
+    __u64 newest_pts;
 };
 
 struct dmx_sec_mem {
-	__u32 buff;
-	__u32 size;
+    __u32 buff;
+    __u32 size;
 };
 #endif
 
 /**
  * struct dmx_pes_filter_params - Specifies Packetized Elementary Stream (PES)
- *	filter parameters.
+ *    filter parameters.
  *
- * @pid:	PID to be filtered.
- * @input:	Demux input, as specified by &enum dmx_input.
- * @output:	Demux output, as specified by &enum dmx_output.
- * @pes_type:	Type of the pes filter, as specified by &enum dmx_pes_type.
- * @flags:	Demux PES flags.
+ * @pid:    PID to be filtered.
+ * @input:    Demux input, as specified by &enum dmx_input.
+ * @output:    Demux output, as specified by &enum dmx_output.
+ * @pes_type:    Type of the pes filter, as specified by &enum dmx_pes_type.
+ * @flags:    Demux PES flags.
  */
 struct dmx_pes_filter_params {
-	__u16           pid;
-	dmx_input_t  input;
-	dmx_output_t output;
-	dmx_pes_type_t pes_type;
-	__u32           flags;
+    __u16           pid;
+    dmx_input_t  input;
+    dmx_output_t output;
+    dmx_pes_type_t pes_type;
+    __u32           flags;
 #ifdef CONFIG_AMLOGIC_DVB_COMPAT
 /*bit 8~15 for mem sec_level*/
 #define DMX_MEM_SEC_LEVEL1   (1 << 10)
@@ -219,7 +219,7 @@
 /*bit 16~23 for output */
 #define DMX_ES_OUTPUT        (1 << 16)
 /*set raw mode, it will send the struct dmx_sec_es_data, not es data*/
-#define DMX_OUTPUT_RAW_MODE	 (1 << 17)
+#define DMX_OUTPUT_RAW_MODE     (1 << 17)
 
 /*24~31 one byte for audio type, dmx_audio_format_t*/
 #define DMX_AUDIO_FORMAT_BIT 24
@@ -228,91 +228,91 @@
 };
 
 typedef struct dmx_caps {
-	__u32 caps;
-	int num_decoders;
+    __u32 caps;
+    int num_decoders;
 } dmx_caps_t;
 
 typedef enum dmx_source {
-	DMX_SOURCE_FRONT0 = 0,
-	DMX_SOURCE_FRONT1,
-	DMX_SOURCE_FRONT2,
-	DMX_SOURCE_FRONT3,
-	DMX_SOURCE_DVR0   = 16,
-	DMX_SOURCE_DVR1,
-	DMX_SOURCE_DVR2,
-	DMX_SOURCE_DVR3,
+    DMX_SOURCE_FRONT0 = 0,
+    DMX_SOURCE_FRONT1,
+    DMX_SOURCE_FRONT2,
+    DMX_SOURCE_FRONT3,
+    DMX_SOURCE_DVR0   = 16,
+    DMX_SOURCE_DVR1,
+    DMX_SOURCE_DVR2,
+    DMX_SOURCE_DVR3,
 
 #ifdef CONFIG_AMLOGIC_DVB_COMPAT
-	DMX_SOURCE_FRONT0_OFFSET = 100,
-	DMX_SOURCE_FRONT1_OFFSET,
-	DMX_SOURCE_FRONT2_OFFSET
+    DMX_SOURCE_FRONT0_OFFSET = 100,
+    DMX_SOURCE_FRONT1_OFFSET,
+    DMX_SOURCE_FRONT2_OFFSET
 #endif
 } dmx_source_t;
 
 struct dmx_stc {
-	unsigned int num;	/* input : which STC? 0..N */
-	unsigned int base;	/* output: divisor for stc to get 90 kHz clock */
-	__u64 stc;		/* output: stc in 'base'*90 kHz units */
+    unsigned int num;    /* input : which STC? 0..N */
+    unsigned int base;    /* output: divisor for stc to get 90 kHz clock */
+    __u64 stc;        /* output: stc in 'base'*90 kHz units */
 };
 
 #ifdef CONFIG_AMLOGIC_DVB_COMPAT
 enum {
-	DMA_0 = 0,
-	DMA_1,
-	DMA_2,
-	DMA_3,
-	DMA_4,
-	DMA_5,
-	DMA_6,
-	DMA_7,
-	FRONTEND_TS0 = 32,
-	FRONTEND_TS1,
-	FRONTEND_TS2,
-	FRONTEND_TS3,
-	FRONTEND_TS4,
-	FRONTEND_TS5,
-	FRONTEND_TS6,
-	FRONTEND_TS7,
-	DMA_0_1 = 64,
-	DMA_1_1,
-	DMA_2_1,
-	DMA_3_1,
-	DMA_4_1,
-	DMA_5_1,
-	DMA_6_1,
-	DMA_7_1,
-	FRONTEND_TS0_1 = 96,
-	FRONTEND_TS1_1,
-	FRONTEND_TS2_1,
-	FRONTEND_TS3_1,
-	FRONTEND_TS4_1,
-	FRONTEND_TS5_1,
-	FRONTEND_TS6_1,
-	FRONTEND_TS7_1,
+    DMA_0 = 0,
+    DMA_1,
+    DMA_2,
+    DMA_3,
+    DMA_4,
+    DMA_5,
+    DMA_6,
+    DMA_7,
+    FRONTEND_TS0 = 32,
+    FRONTEND_TS1,
+    FRONTEND_TS2,
+    FRONTEND_TS3,
+    FRONTEND_TS4,
+    FRONTEND_TS5,
+    FRONTEND_TS6,
+    FRONTEND_TS7,
+    DMA_0_1 = 64,
+    DMA_1_1,
+    DMA_2_1,
+    DMA_3_1,
+    DMA_4_1,
+    DMA_5_1,
+    DMA_6_1,
+    DMA_7_1,
+    FRONTEND_TS0_1 = 96,
+    FRONTEND_TS1_1,
+    FRONTEND_TS2_1,
+    FRONTEND_TS3_1,
+    FRONTEND_TS4_1,
+    FRONTEND_TS5_1,
+    FRONTEND_TS6_1,
+    FRONTEND_TS7_1,
 };
 
 /*define filter mem_info type*/
 enum {
-	DMX_VIDEO_TYPE = 0,
-	DMX_AUDIO_TYPE,
-	DMX_SUBTITLE_TYPE,
-	DMX_TELETEXT_TYPE,
-	DMX_SECTION_TYPE,
+    DMX_VIDEO_TYPE = 0,
+    DMX_AUDIO_TYPE,
+    DMX_SUBTITLE_TYPE,
+    DMX_TELETEXT_TYPE,
+    DMX_SECTION_TYPE,
 };
 
 struct filter_mem_info {
-	__u32 type;
-	__u32 pid;
-	struct dmx_mem_info	filter_info;
+    __u32 type;
+    __u32 pid;
+    struct dmx_mem_info    filter_info;
 };
 
 struct dmx_filter_mem_info {
-	__u32 filter_num;
-	struct filter_mem_info info[40];
+    __u32 filter_num;
+    struct filter_mem_info info[40];
 };
 
 struct dvr_mem_info {
-	__u32 wp_offset;
+    __u32 wp_offset;
 };
 #endif
 
@@ -334,8 +334,8 @@
 #define DMX_GET_HW_SOURCE       _IOR('o', 83, int)
 #define DMX_GET_FILTER_MEM_INFO _IOR('o', 84, struct dmx_filter_mem_info)
 /*just for dvr sec mem, please call before DMX_SET_PES_FILTER*/
-#define DMX_SET_SEC_MEM			_IOW('o', 85, struct dmx_sec_mem)
-#define DMX_GET_DVR_MEM			_IOR('o', 86, struct dvr_mem_info)
+#define DMX_SET_SEC_MEM            _IOW('o', 85, struct dmx_sec_mem)
+#define DMX_GET_DVR_MEM            _IOR('o', 86, struct dvr_mem_info)
 #define DMX_REMAP_PID           _IOR('o', 87, __u16[2])
 #endif
 
diff --git a/include/dvb_dmx_wrapper.h b/include/dvb_dmx_wrapper.h
index 0a974ee..a2b761b 100644
--- a/include/dvb_dmx_wrapper.h
+++ b/include/dvb_dmx_wrapper.h
@@ -9,7 +9,7 @@
  * @brief   linux dvb demux wrapper
  * @file    dvb_dmx_wrapper.h
  *
- * \author chuanzhi wang <chaunzhi.wang@amlogic.com>
+ * \author chuanzhi wang <chuanzhi.wang@amlogic.com>
  * \date 2020-07-16: create the document
  ***************************************************************************/
 
@@ -25,78 +25,78 @@
 
 typedef void (*AML_DMX_DataCb)(int dev_no, int fd, const uint8_t *data, int len, void *user_data);
 
-	/**\brief dmx device init, creat dmx thread
+    /**\brief dmx device init, creat dmx thread
  * \param dmx device number
  * \return DVB_SUCCESS On success, DVB_FAILURE on error.
  */
-	DVB_RESULT AML_DMX_Open(int dev_no);
+    DVB_RESULT AML_DMX_Open(int dev_no);
 
-	/**\brief dmx device uninit, destroy dmx thread
+    /**\brief dmx device uninit, destroy dmx thread
  * \param dmx device number
  * \return DVB_SUCCESS On success, DVB_FAILURE on error.
  */
-	DVB_RESULT AML_DMX_Close(int dev_no);
+    DVB_RESULT AML_DMX_Close(int dev_no);
 
-	/**\brief allocate dmx filter
+    /**\brief allocate dmx filter
  * \param dmx device number
  * \param get dmx filter index
  * \return DVB_SUCCESS On success, DVB_FAILURE on error.
  */
-	DVB_RESULT AML_DMX_AllocateFilter(int dev_no, int *fhandle);
+    DVB_RESULT AML_DMX_AllocateFilter(int dev_no, int *fhandle);
 
-	/**\brief set demux section filter
+    /**\brief set demux section filter
  * \param dmx device number
  * \param dmx filter index
  * \param dmx section filter param
  * \return DVB_SUCCESS On success, DVB_FAILURE on error.
  */
-	DVB_RESULT AML_DMX_SetSecFilter(int dev_no, int fhandle, const struct dmx_sct_filter_params *params);
+    DVB_RESULT AML_DMX_SetSecFilter(int dev_no, int fhandle, const struct dmx_sct_filter_params *params);
 
-	/**\brief set demux pes filter
+    /**\brief set demux pes filter
  * \param dmx device number
  * \param dmx filter index
  * \param dmx pes filter param
  * \return DVB_SUCCESS On success, DVB_FAILURE on error.
  */
-	DVB_RESULT AML_DMX_SetPesFilter(int dev_no, int fhandle, const struct dmx_pes_filter_params *params);
+    DVB_RESULT AML_DMX_SetPesFilter(int dev_no, int fhandle, const struct dmx_pes_filter_params *params);
 
-	/**\brief set demux filter buffer
+    /**\brief set demux filter buffer
  * \param dmx device number
  * \param dmx filter index
  * \param dmx filter buffer size
  * \return DVB_SUCCESS On success, DVB_FAILURE on error.
  */
-	DVB_RESULT AML_DMX_SetBufferSize(int dev_no, int fhandle, int size);
+    DVB_RESULT AML_DMX_SetBufferSize(int dev_no, int fhandle, int size);
 
-	/**\brief free demux filter
+    /**\brief free demux filter
  * \param dmx device number
  * \param dmx filter index
  * \return DVB_SUCCESS On success, DVB_FAILURE on error.
  */
-	DVB_RESULT AML_DMX_FreeFilter(int dev_no, int fhandle);
+    DVB_RESULT AML_DMX_FreeFilter(int dev_no, int fhandle);
 
-	/**\brief start demux filter
+    /**\brief start demux filter
  * \param dmx device number
  * \param dmx filter index
  * \return DVB_SUCCESS On success, DVB_FAILURE on error.
  */
-	DVB_RESULT AML_DMX_StartFilter(int dev_no, int fhandle);
+    DVB_RESULT AML_DMX_StartFilter(int dev_no, int fhandle);
 
-	/**\brief stop demux filter
+    /**\brief stop demux filter
  * \param dmx device number
  * \param dmx filter index
  * \return DVB_SUCCESS On success, DVB_FAILURE on error.
  */
-	DVB_RESULT AML_DMX_StopFilter(int dev_no, int fhandle);
+    DVB_RESULT AML_DMX_StopFilter(int dev_no, int fhandle);
 
-	/**\brief set demux callback
+    /**\brief set demux callback
  * \param dmx device number
  * \param dmx filter index
  * \param dmx filter callback
  * \param dmx filter callback param
  * \return DVB_SUCCESS On success, DVB_FAILURE on error.
  */
-	DVB_RESULT AML_DMX_SetCallback(int dev_no, int fhandle, AML_DMX_DataCb cb, void *user_data);
+    DVB_RESULT AML_DMX_SetCallback(int dev_no, int fhandle, AML_DMX_DataCb cb, void *user_data);
 
 #ifdef __cplusplus
 }
diff --git a/include/dvb_frontend_wrapper.h b/include/dvb_frontend_wrapper.h
index 4543ecd..3cfd907 100644
--- a/include/dvb_frontend_wrapper.h
+++ b/include/dvb_frontend_wrapper.h
@@ -9,7 +9,7 @@
  * @brief   linux dvb frontend wrapper
  * @file    dvb_dmx_frontend.h
  *
- * \author chuanzhi wang <chaunzhi.wang@amlogic.com>
+ * \author chuanzhi wang <chuanzhi.wang@amlogic.com>
  * \date 2020-09-11: create the document
  ***************************************************************************/
 
@@ -173,7 +173,7 @@
   {
     TUNER_STATE_LOCKED,
     TUNER_STATE_TIMEOUT,
-    TUNER_STATE_UNKNOW
+    TUNER_STATE_UNKNOWN
   } dmd_tuner_event_t;
 
   typedef struct
@@ -276,7 +276,7 @@
  * \param FE device fd
  * \return DVB_SUCCESS On success, DVB_FAILURE on error.
  */
-  DVB_RESULT AML_FE_Colse(int frontend_fd);
+  DVB_RESULT AML_FE_Close(int frontend_fd);
 
   /**\brief get current tune status
  * \param FE device fd
diff --git a/include/dvb_utils.h b/include/dvb_utils.h
index dca2d45..20571ab 100644
--- a/include/dvb_utils.h
+++ b/include/dvb_utils.h
@@ -9,6 +9,7 @@
 #include <android/log.h>
 #include <stdio.h>
 #include <inttypes.h>
+#include "dvr_types.h"
 
 #ifdef __cplusplus
 extern "C" {
@@ -20,25 +21,18 @@
     DVB_SUCCESS = 0
   } DVB_RESULT;
 
-/**Logcat TAG of dvb*/
-#define DVB_LOG_TAG "dvb_debug"
-/**Default debug level*/
-#define DVB_DEBUG_LEVEL 1
-
-/**Log output*/
-#define dvb_log_print(...) __android_log_print(ANDROID_LOG_INFO, DVB_LOG_TAG, __VA_ARGS__)
 
 #ifndef __ANDROID_API__
 typedef unsigned int uint_t;
 #endif
 
-/**Output debug message.*/
-#define DVB_DEBUG(_level, _fmt...) \
-  do                               \
-  {                                \
-    if (_level <= DVB_DEBUG_LEVEL) \
-      dvb_log_print(_fmt);         \
-  } while (0)
+/**Log facilities*/
+#define DVB_LOG_TAG "libdvr-dvb"
+#define DVB_DEBUG(...) DVR_LOG_PRINT(LOG_LV_DEBUG, DVB_LOG_TAG, __VA_ARGS__)
+#define DVB_INFO(...) DVR_LOG_PRINT(LOG_LV_INFO, DVB_LOG_TAG, __VA_ARGS__)
+#define DVB_WARN(...) DVR_LOG_PRINT(LOG_LV_WARN, DVB_LOG_TAG, __VA_ARGS__)
+#define DVB_ERROR(...) DVR_LOG_PRINT(LOG_LV_ERROR, DVB_LOG_TAG, __VA_ARGS__)
+#define DVB_FATAL(...) DVR_LOG_PRINT(LOG_LV_FATAL, DVB_LOG_TAG, __VA_ARGS__)
 
   /**Demux input source.*/
   typedef enum
diff --git a/include/dvr_mutex.h b/include/dvr_mutex.h
new file mode 100644
index 0000000..d764ba3
--- /dev/null
+++ b/include/dvr_mutex.h
@@ -0,0 +1,48 @@
+#ifndef _DVR_MUTEX_H_
+#define _DVR_MUTEX_H_
+
+#include <pthread.h>
+
+typedef struct dvr_mutex_s
+{
+   pthread_mutex_t lock;
+   pthread_t thread;
+   int lock_cnt;
+} dvr_mutex_t;
+
+void _dvr_mutex_init(void *mutex);
+void _dvr_mutex_lock(void *mutex);
+void _dvr_mutex_unlock(void *mutex);
+void _dvr_mutex_destroy(void *mutex);
+int _dvr_mutex_save(void *mutex);
+void _dvr_mutex_restore(void *mutex, int val);
+
+#define DVR_MUTEX_DEBUG
+
+#ifndef DVR_MUTEX_DEBUG
+
+#define dvr_mutex_init(a)        _dvr_mutex_init(a)
+#define dvr_mutex_lock(a)        _dvr_mutex_lock(a)
+#define dvr_mutex_unlock(a)      _dvr_mutex_unlock(a)
+#define dvr_mutex_destroy(a)     _dvr_mutex_destroy(a)
+#define dvr_mutex_save(a)        _dvr_mutex_save(a)
+#define dvr_mutex_restore(a, v)  _dvr_mutex_restore(a, v)
+
+#else/*DEBUG*/
+
+void _dvr_mutex_init_dbg(void *mutex, const char *file, int line);
+void _dvr_mutex_lock_dbg(void *mutex, const char *file, int line);
+void _dvr_mutex_unlock_dbg(void *mutex, const char *file, int line);
+void _dvr_mutex_destroy_dbg(void *mutex, const char *file, int line);
+int _dvr_mutex_save_dbg(void *mutex, const char *file, int line);
+void _dvr_mutex_restore_dbg(void *mutex, int val, const char *file, int line);
+#define dvr_mutex_init(a)        _dvr_mutex_init_dbg(a, __FUNCTION__, __LINE__)
+#define dvr_mutex_lock(a)        _dvr_mutex_lock_dbg(a, __FUNCTION__, __LINE__)
+#define dvr_mutex_unlock(a)      _dvr_mutex_unlock_dbg(a, __FUNCTION__, __LINE__)
+#define dvr_mutex_destroy(a)     _dvr_mutex_destroy_dbg(a, __FUNCTION__, __LINE__)
+#define dvr_mutex_save(a)        _dvr_mutex_save_dbg(a, __FUNCTION__, __LINE__)
+#define dvr_mutex_restore(a, v)  _dvr_mutex_restore_dbg(a, v, __FUNCTION__, __LINE__)
+
+#endif/*DEBUG*/
+
+#endif/*_DVR_MUTEX_H_*/
diff --git a/include/dvr_playback.h b/include/dvr_playback.h
index 1d8a43d..6424ff0 100644
--- a/include/dvr_playback.h
+++ b/include/dvr_playback.h
@@ -11,6 +11,7 @@
 #include "AmTsPlayer.h"
 #include "dvr_types.h"
 #include "dvr_crypto.h"
+#include "dvr_mutex.h"
 
 #ifdef __cplusplus
 extern "C" {
@@ -139,7 +140,7 @@
 typedef enum
 {
   DVR_PLAYBACK_PID_ERROR,            /**< uninit state */
-  DVR_PLAYBACK_FMT_ERROR           /**< fmt not surport backword */
+  DVR_PLAYBACK_FMT_ERROR           /**< fmt not support backword */
 } DVR_PlaybackError_t;
 
 
@@ -158,8 +159,10 @@
 {
   DVR_PlaybackPlayState_t state;  /**< playback play state */
   uint64_t segment_id;                 /**< playback ongoing segment index */
-  uint32_t time_cur;                   /**< playback cur time,0 <--> time_end Ms*/
-  uint32_t time_end;                   /**< playback ongoing segment dur,Ms */
+  int32_t time_cur;               /**< current playback time position in ms of a segment.
+                                   It can be a negative value to refer to relative time
+                                   position of previous segment*/
+  int32_t time_end;               /**< end time position of a segment in ms */
   DVR_PlaybackPids_t pids;        /**< playback played pids */
   int                    speed;  /**< playback speed */
   DVR_PlaybackSegmentFlag_t flags; /**< playback played segment flag */
@@ -182,7 +185,7 @@
   DVR_PLAYBACK_EVENT_NO_KEY,                        /**< no key*/
   DVR_PLAYBACK_EVENT_REACHED_BEGIN     ,            /**< reached begin*/
   DVR_PLAYBACK_EVENT_REACHED_END,                    /**< reached end*/
-  DVR_PLAYBACK_EVENT_NOTIFY_PLAYTIME,               /**< notify play cur segmeng time ms*/
+  DVR_PLAYBACK_EVENT_NOTIFY_PLAYTIME,               /**< notify play cur segment time ms*/
   DVR_PLAYBACK_EVENT_FIRST_FRAME,                   /**< first frame*/
   DVR_PLAYBACK_EVENT_NODATA,                        /**< no data*/
   DVR_PLAYBACK_EVENT_DATARESUME                     /**< data resume*/
@@ -220,7 +223,7 @@
   DVR_CryptoFunction_t   crypto_fn;       /**< Crypto function.*/
   void                   *crypto_data;    /**< Crypto function's user data.*/
   uint8_t                *clearkey;       /**< key for encrypted PVR on FTA.*/
-  uint8_t                *cleariv;        /**< iv for encrpted PVR on FTA.*/
+  uint8_t                *cleariv;        /**< iv for encrypted PVR on FTA.*/
   uint32_t               keylen;          /**< key/iv length.*/
   DVR_Bool_t             has_pids;        /**< has video audo pid fmt info*/
   DVR_PlaybackEventFunction_t  event_fn;           /**< playback event callback function*/
@@ -234,19 +237,19 @@
 {
   DVR_PLAYBACK_CMD_START,               /**< start av */
   DVR_PLAYBACK_CMD_STOP,                /**< stop av */
-  DVR_PLAYBACK_CMD_VSTART,              /**< v start */
-  DVR_PLAYBACK_CMD_ASTART   ,           /**< a start */
-  DVR_PLAYBACK_CMD_VSTOP  ,             /**< v stop */
-  DVR_PLAYBACK_CMD_ASTOP,               /**< a stop */
-  DVR_PLAYBACK_CMD_VRESTART,            /**< v restart */
-  DVR_PLAYBACK_CMD_ARESTART,            /**< a restart */
-  DVR_PLAYBACK_CMD_AVRESTART,            /**< av restart */
-  DVR_PLAYBACK_CMD_VSTOPASTART,         /**< v stop a start*/
-  DVR_PLAYBACK_CMD_ASTOPVSTART,         /**< a stop vstart */
-  DVR_PLAYBACK_CMD_VSTOPARESTART,       /**<v stop a restart*/
-  DVR_PLAYBACK_CMD_ASTOPVRESTART,       /**<a stop v restart*/
-  DVR_PLAYBACK_CMD_VSTARTARESTART,       /**<v start a restart*/
-  DVR_PLAYBACK_CMD_ASTARTVRESTART,       /**<a start v restart*/
+  DVR_PLAYBACK_CMD_V_START,              /**< v start */
+  DVR_PLAYBACK_CMD_A_START   ,           /**< a start */
+  DVR_PLAYBACK_CMD_V_STOP  ,             /**< v stop */
+  DVR_PLAYBACK_CMD_A_STOP,               /**< a stop */
+  DVR_PLAYBACK_CMD_V_RESTART,            /**< v restart */
+  DVR_PLAYBACK_CMD_A_RESTART,            /**< a restart */
+  DVR_PLAYBACK_CMD_AV_RESTART,            /**< av restart */
+  DVR_PLAYBACK_CMD_V_STOP_A_START,         /**< v stop a start*/
+  DVR_PLAYBACK_CMD_A_STOP_V_START,         /**< a stop v_start */
+  DVR_PLAYBACK_CMD_V_STOP_A_RESTART,       /**<v stop a restart*/
+  DVR_PLAYBACK_CMD_A_STOP_V_RESTART,       /**<a stop v restart*/
+  DVR_PLAYBACK_CMD_V_START_A_RESTART,       /**<v start a restart*/
+  DVR_PLAYBACK_CMD_A_START_V_RESTART,       /**<a start v restart*/
   DVR_PLAYBACK_CMD_PAUSE,               /**< pause */
   DVR_PLAYBACK_CMD_RESUME,              /**< resume */
   DVR_PLAYBACK_CMD_SEEK,                /**< seek */
@@ -295,7 +298,7 @@
   DVR_PlaybackSegmentInfo_t  last_segment;          /**< last playing segment*/
   struct list_head           segment_list;         /**< segment list head*/
   pthread_t                  playback_thread;    /**< playback thread*/
-  pthread_mutex_t            lock;               /**< playback lock*/
+  dvr_mutex_t                lock;               /**< playback lock*/
   pthread_mutex_t            segment_lock;      /**< playback segment lock*/
   pthread_cond_t             cond;               /**< playback cond*/
   void                       *user_data;         /**< playback userdata, used to send event*/
@@ -336,7 +339,7 @@
   DVR_PlaybackVendor_t       vendor;
   int                        noData;
   DVR_Bool_t                 seek_pause;                /**<set true when user call seek at pause state,we will start inject data, if first frame is got,set false and stop inject data*/
-  int                        last_segment_tatol;        /**< last segment tatol time*/
+  int                        last_segment_total;        /**< last segment total time*/
 
   DVR_PlaybackConSpe_t       con_spe;   /**< inject data speed info*/
 
@@ -346,9 +349,16 @@
   uint32_t                       limit;            /**< rec data limit time in ms*/
   //first play need seek to start time
   uint32_t                   first_start_time;
+  //The segment id where a playback is initially started
+  uint64_t                   first_start_id;
+  //Determine whether it is needed to check the cache value from AmTsPlayer_getDelayTime
+  //It is only allowed to check cache one time in a single playback
+  DVR_Bool_t                 check_cache_flag;
   DVR_Bool_t                 need_seek_start;
   //init fake pid
   int                         fake_pid;
+  //Audio presentation id, used for dolby AC4 audio
+  int32_t                     audio_presentation_id;
 } DVR_Playback_t;
 /**\endcond*/
 
@@ -368,7 +378,7 @@
 int dvr_playback_close(DVR_PlaybackHandle_t handle);
 
 
-/**\brief Start play audio and video, used start auido api and start video api
+/**\brief Start play audio and video, used start audio api and start video api
  * \param[in] handle playback handle
  * \param[in] flag playback flag
  * \retval DVR_SUCCESS On success
@@ -436,11 +446,11 @@
 /**\brief Start audio playing
  * \param[in] handle playback handle
  * \param[in] params audio playback params,contains fmt and pid...
- * \param[in] adparams ad audio playback params,contains fmt and pid...
+ * \param[in] ad_params ad audio playback params,contains fmt and pid...
  * \retval DVR_SUCCESS On success
  * \return Error code
  */
-int dvr_playback_audio_start(DVR_PlaybackHandle_t handle, am_tsplayer_audio_params *param, am_tsplayer_audio_params *adparam);
+int dvr_playback_audio_start(DVR_PlaybackHandle_t handle, am_tsplayer_audio_params *param, am_tsplayer_audio_params *ad_param);
 
 
 /**\brief Stop audio playing
@@ -578,6 +588,14 @@
  */
 DVR_Bool_t dvr_playback_check_limit(DVR_PlaybackHandle_t handle);
 
+/**\brief set ac4 audio preselection id for playback
+ * \param[in] handle, DVR playback session handle
+ * \param[in] presel_id, ac4 preselection id
+ * \return DVR_SUCCESS on success
+ * \return error code on failure
+ */
+int dvr_playback_set_ac4_preselection_id(DVR_PlaybackHandle_t handle, int presel_id);
+
 #ifdef __cplusplus
 }
 #endif
diff --git a/include/dvr_record.h b/include/dvr_record.h
index ab7fb9f..626250a 100644
--- a/include/dvr_record.h
+++ b/include/dvr_record.h
@@ -66,14 +66,14 @@
 {
   DVR_Bool_t              transition;     /**< DVR_TRUE is transition, DVR_FALSE is not transition. At the start of a recording this shall be set to DVR_TRUE*/
   DVR_CryptoParity_t      parity;         /**< The crypto parity at the ts_offset*/
-  loff_t                  ts_offset;      /**< TS packet offset correspongding to this crypto period*/
+  loff_t                  ts_offset;      /**< TS packet offset corresponding to this crypto period*/
   DVR_CryptoFilterType_t  filter_type;    /**< Indicate this notification concerns audio or video*/
 } DVR_CryptoPeriodInfo_t;
 
 /**\brief DVR crypto period information*/
 typedef struct {
-  uint64_t                      interval_bytes;         /**< The inteval between two regular notification of crypto period. For example, if the current segment is always ODD for a long time, record module would notify the current crypto period status when segment size reached the interval_bytes*/
-  DVR_Bool_t                    notify_clear_periods;   /**< Inticate whether it shall track the transition to clear period. DVR_TRUE means it shall not notify clear periods, but only transition between ODD and EVEN. DVR_FALSE means it shall notify transition between ODD, EVEN and clear periods*/
+  uint64_t                      interval_bytes;         /**< The interval between two regular notification of crypto period. For example, if the current segment is always ODD for a long time, record module would notify the current crypto period status when segment size reached the interval_bytes*/
+  DVR_Bool_t                    notify_clear_periods;   /**< Indicate whether it shall track the transition to clear period. DVR_TRUE means it shall not notify clear periods, but only transition between ODD and EVEN. DVR_FALSE means it shall notify transition between ODD, EVEN and clear periods*/
 } DVR_CryptoPeriod_t;
 
 /**\brief DVR record event notify function*/
@@ -88,11 +88,14 @@
   int                         flush_size;         /**< DVR record interrupt flush size*/
   DVR_RecordEventFunction_t   event_fn;           /**< DVR record event callback function*/
   void                        *event_userdata;    /**< DVR event userdata*/
-  size_t                      notification_size;  /**< DVR record notification size, record moudle would send a notifaction when the size of current segment is multiple of this value. Put 0 in this argument if you don't want to receive the notification*/
+  size_t                      notification_size;  /**< DVR record notification size, record module would send a notification when the size of current segment is multiple of this value. Put 0 in this argument if you don't want to receive the notification*/
   uint8_t                     *clearkey;          /**< key for encrypted PVR on FTA.*/
-  uint8_t                     *cleariv;           /**< iv for encrpted PVR on FTA.*/
+  uint8_t                     *cleariv;           /**< iv for encrypted PVR on FTA.*/
   uint32_t                    keylen;             /**< key/iv length.*/
   int                         ringbuf_size;       /**< DVR record ring buf size*/
+  int                         notification_time;  /**< DVR record notification time, record module would send a notification when the size of current segment is multiple of this value. Put 0 in this argument if you don't want to receive the notification*/
+  DVR_Bool_t                  force_sysclock;     /**< If ture, force to use system clock as PVR index time source. If false, libdvr can determine index time source based on actual situation*/
+  loff_t                      guarded_segment_size;   /**< Guarded segment size in bytes. Libdvr will be forcely stopped to write anymore if current segment reaches this size*/
 } DVR_RecordOpenParams_t;
 
 /**\brief DVR record segment start parameters*/
@@ -187,7 +190,7 @@
 
 /**\brief DVR record write data, used for VOD mode
  * \param[in] handle DVR recording session handle
- * \param[in] buffer The redcord data buffer
+ * \param[in] buffer The record data buffer
  * \param[in] len The record data length
  * \return DVR_SUCCESS on success
  * \return error code on failure
@@ -227,6 +230,15 @@
  * \return secure or free.
  */
 int dvr_record_is_secure_mode(DVR_RecordHandle_t handle);
+
+/**\brief Turn on/off recording data discarding
+ * \param[in] handle, DVR recording session handle
+ * \param[in] discard, 0: normal processing, 1: discard coming recording data
+ * \return DVR_SUCCESS on success
+ * \return error code on failure
+ */
+int dvr_record_discard_coming_data(DVR_RecordHandle_t handle, DVR_Bool_t discard);
+
 #ifdef __cplusplus
 }
 #endif
diff --git a/include/dvr_segment.h b/include/dvr_segment.h
index 1a27d5a..0c11859 100644
--- a/include/dvr_segment.h
+++ b/include/dvr_segment.h
@@ -52,6 +52,16 @@
  */
 int dvr_segment_get_info(const char *location, uint64_t segment_id, DVR_RecordSegmentInfo_t *p_info);
 
+/**\brief Get the segment's information
+ * \param[in] location The record file's location
+ * \param[in] segment_id The segment index
+ * \param[out] p_info Return the segment's information
+ * \return DVR_SUCCESS On success
+ * \return Error code On failure
+ */
+
+int dvr_segment_get_allInfo(const char *location, struct list_head *list);
+
 /**\brief Link a segment group as the record file's list
  * \param[in] location The record file's location
  * \param[in] nb_segments The number of segments
@@ -62,8 +72,8 @@
 int dvr_segment_link(const char *location, uint32_t nb_segments, uint64_t *p_segment_ids);
 
 
-#define LSEG_OP_NEW 0
-#define LSEG_OP_ADD 1
+#define SEGMENT_OP_NEW 0
+#define SEGMENT_OP_ADD 1
 int dvr_segment_link_op(const char *location, uint32_t nb_segments, uint64_t *p_segment_ids, int op);
 
 #ifdef __cplusplus
diff --git a/include/dvr_types.h b/include/dvr_types.h
index 727d73a..2b00ae4 100644
--- a/include/dvr_types.h
+++ b/include/dvr_types.h
@@ -22,6 +22,7 @@
 #include <assert.h>
 #include <pthread.h>
 
+#include "list.h"
 #include <android/log.h>
 
 #ifndef __ANDROID_API__
@@ -33,7 +34,6 @@
 {
 #endif
 
-
 /*****************************************************************************
 * Global Definitions
 *****************************************************************************/
@@ -43,34 +43,36 @@
 /**Maximum path size.*/
 #define DVR_MAX_LOCATION_SIZE     512
 
-/**Logcat TAG of libdvr*/
+/**Log facilities.*/
+#define LOG_LV_DEFAULT 1
+#define LOG_LV_VERBOSE 2
+#define LOG_LV_DEBUG 3
+#define LOG_LV_INFO 4
+#define LOG_LV_WARN 5
+#define LOG_LV_ERROR 6
+#define LOG_LV_FATAL 7
+
 #define DVR_LOG_TAG "libdvr"
-/**Default debug level*/
-#define DVR_DEBUG_LEVEL 1
+#define DVR_DEBUG(...) DVR_LOG_PRINT(LOG_LV_DEBUG, DVR_LOG_TAG, __VA_ARGS__)
+#define DVR_INFO(...) DVR_LOG_PRINT(LOG_LV_INFO, DVR_LOG_TAG, __VA_ARGS__)
+#define DVR_WARN(...) DVR_LOG_PRINT(LOG_LV_WARN, DVR_LOG_TAG, __VA_ARGS__)
+#define DVR_ERROR(...) DVR_LOG_PRINT(LOG_LV_ERROR, DVR_LOG_TAG, __VA_ARGS__)
+#define DVR_FATAL(...) DVR_LOG_PRINT(LOG_LV_FATAL, DVR_LOG_TAG, __VA_ARGS__)
 
-/**Log output*/
-#define dvr_log_print(...) __android_log_print(ANDROID_LOG_INFO, DVR_LOG_TAG, __VA_ARGS__)
-#define dvr_log_print_fl(tag, fmt, ...)\
-  __android_log_print(ANDROID_LOG_INFO, DVR_LOG_TAG, tag " %s %d: " fmt, __FUNCTION__, __LINE__, ##__VA_ARGS__)
+extern int g_dvr_log_level;
 
-/**Output debug message.*/
-#define DVR_DEBUG(_level,_fmt...) \
-  do {\
-    if (_level <= DVR_DEBUG_LEVEL)\
-      dvr_log_print(_fmt);\
-  } while (0)
-
-#define DVR_DEBUG_FL(_level, _tag, _fmt...) \
-  do {\
-    if (_level <= DVR_DEBUG_LEVEL)\
-      dvr_log_print_fl(_tag, _fmt);\
-  } while (0)
+#define DVR_LOG_PRINT(level,tag,...) \
+  do { \
+    if (level>=g_dvr_log_level) { \
+      __android_log_print(level,tag,__VA_ARGS__); \
+    } \
+  }while(0)
 
 /**Abort the program if assertion is false.*/
 #define DVR_ASSERT(expr) \
   do {\
     if (!(expr)) {\
-      DVR_DEBUG(1, "%s-%d failed", __func__, __LINE__);\
+      DVR_FATAL("at %s:%d, \'"#expr"\' is false then asserts", __func__, __LINE__);\
       assert(expr);\
     }\
   } while (0)
@@ -79,7 +81,7 @@
 #define DVR_RETURN_IF_FALSE(expr)\
   do {\
     if (!(expr)) {\
-      DVR_DEBUG(1, "%s-%d failed", __func__, __LINE__);\
+      DVR_ERROR("at %s:%d, \'"#expr"\' is false then returns failure", __func__, __LINE__);\
       return DVR_FAILURE;\
     }\
   } while (0);
@@ -88,7 +90,7 @@
 #define DVR_RETURN_IF_FALSE_WITH_UNLOCK(expr, lock)\
   do {\
     if (!(expr)) {\
-      DVR_DEBUG(1, "%s-%d failed", __func__, __LINE__);\
+      DVR_ERROR("at %s:%d, \'"#expr"\' is false then unlocks and returns failure", __func__, __LINE__);\
       pthread_mutex_unlock(lock);\
       return DVR_FAILURE;\
     }\
@@ -107,11 +109,11 @@
 #define DVR_FALSE       (0)
 #endif
 
-#ifndef UNDVRUSED
-#define UNDVRUSED(x) (void)(x)
+#ifndef DVR_UNUSED
+#define DVR_UNUSED(x) (void)(x)
 #endif
 
-/**Funciton result*/
+/**Function result*/
 typedef enum {
   DVR_FAILURE = -1, /**< Generic error.*/
   DVR_SUCCESS = 0   /**< Success*/
@@ -126,9 +128,6 @@
 /**PTS.*/
 typedef uint64_t DVR_Pts_t;
 
-/**Invalid PTS value.*/
-#define DVR_INVALID_PTS 0xffffffffffffffffull
-
 /**Stream type.*/
 typedef enum {
   DVR_STREAM_TYPE_VIDEO,     /**< Video stream.*/
@@ -201,6 +200,7 @@
 
 /**\brief Segment store information*/
 typedef struct {
+  struct  list_head   head;         /**< Segment node.*/
   uint64_t            id;                                         /**< DVR segment id*/
   uint32_t            nb_pids;                                    /**< DVR segment number of pids*/
   DVR_StreamPid_t     pids[DVR_MAX_RECORD_PIDS_COUNT];            /**< DVR pids information*/
diff --git a/include/dvr_utils.h b/include/dvr_utils.h
index 145ae09..c070f99 100644
--- a/include/dvr_utils.h
+++ b/include/dvr_utils.h
@@ -10,99 +10,53 @@
 extern "C" {
 #endif
 
-
-/**\brief read sysfs node
- *  name file name
- *  buf  store sysfs value buf
- *  len  buf len
- */
-typedef void (*DVR_Read_Sysfs_Cb)(const char *name, char *buf, int len);
-
-/**\brief write sysfs
- *  name file name
- *  cmd  write to sysfs node cmd
- */
-typedef void (*DVR_Write_Sysfs_Cb)(const char *name, const char *cmd);
-
-/**\brief read prop
- *  name prop name
- *  buf  store prop value buf
- *  len  buf len
- */
-typedef void (*DVR_Read_Prop_Cb)(const char *name, char *buf, int len);
-
-/**\brief write prop
- *  name prop name
- *  cmd  write to prop node cmd
- */
-typedef void (*DVR_Write_Prop_Cb)(const char *name, const char *cmd);
-
-
-/**\brief regist rw sysfs cb
- * \param[in] fun callback
- * \return
- *   - DVR_SUCCESS
- *   - error
- */
-int dvr_register_rw_sys(DVR_Read_Sysfs_Cb RCb, DVR_Write_Sysfs_Cb WCb);
-
-/**\brief unregist rw sys cb
- */
-int dvr_unregister_rw_sys(void);
-
-
-/**\brief regist rw prop cb
- * \param[in] fun callback
- * \return
- *   - DVR_SUCCESS
- *   - error
- */
-
-int dvr_rgister_rw_prop(DVR_Read_Prop_Cb RCb, DVR_Write_Prop_Cb WCb);
-
-/**\brief unregist rw prop cb */
-int dvr_unregister_rw_prop(void);
-
-
 /**\brief Write a string cmd to a file
  * \param[in] name File name
  * \param[in] cmd String command
  * \return DVR_SUCCESS On success
  * \return Error code On failure
  */
-
 int dvr_file_echo(const char *name, const char *cmd);
 
-
 /**\brief read sysfs file
  * \param[in] name, File name
  * \param[out] buf, store sysfs node value
  * \return DVR_SUCCESS On success
  * \return Error code On failure
  */
-
 int dvr_file_read(const char *name, char *buf, int len);
 
-
-/**\brief Write a string cmd to a prop
- * \param[in] name, prop name
- * \param[in] cmd, String command
+/**\brief read property value
+ * \param[in] name, property name
+ * \param[out] buf, property value
  * \return DVR_SUCCESS On success
- * \return Error code On failure
+ * \return DVR_FAILURE On failure
  */
-
-int dvr_prop_echo(const char *name, const char *cmd);
-
-
-/**\brief read prop value
- * \param[in] name, prop name
- * \param[out] buf, store prop node value
- * \return DVR_SUCCESS On success
- * \return Error code On failure
- */
-
 int dvr_prop_read(const char *name, char *buf, int len);
 
+/**\brief write property value
+ * \param[in] name, property name
+ * \param[in] value, property value
+ * \return DVR_SUCCESS On success
+ * \return DVR_FAILURE On failure
+ */
+int dvr_prop_write(const char *name, char *value);
+
+/**\brief read int type property value
+ * \param[in] name, property name
+ * \param[in] def, default property value in case any failure
+ * \return int type property value. If any failure default value will be returned instead
+ */
+int dvr_prop_read_int(const char *name, int def);
+
+/**\brief calculates the difference between ts1 and ts2
+ * \param[in] ts1, higher bound of the timespec* whose length is calculated
+ * \param[in] ts2, lower bound of the timespec* whose length is calculated
+ * \param[out] ts3, The result timespec* of (ts1-ts2)
+ * \return void
+ */
+void clock_timespec_subtract(struct timespec *ts1, struct timespec *ts2, struct timespec *ts3);
+
 #ifdef __cplusplus
 }
 #endif
diff --git a/include/dvr_wrapper.h b/include/dvr_wrapper.h
index 7b0323b..2917dc7 100644
--- a/include/dvr_wrapper.h
+++ b/include/dvr_wrapper.h
@@ -53,11 +53,12 @@
 typedef struct {
   DVR_PlaybackPlayState_t state;      /**< DVR playback state*/
   DVR_WrapperInfo_t info_cur;         /**< DVR playback current information*/
-  DVR_WrapperInfo_t info_full;        /**< DVR playback total(non-obsolete) infomation*/
+  DVR_WrapperInfo_t info_full;        /**< DVR playback total(non-obsolete) information*/
   DVR_PlaybackPids_t pids;            /**< DVR playback pids information*/
   float speed;                        /**< DVR playback current speed*/
   DVR_PlaybackSegmentFlag_t flags;    /**< DVR playback flags*/
   DVR_WrapperInfo_t info_obsolete;    /**< DVR playback obsolete information, take into account for timeshift*/
+  DVR_WrapperInfo_t disguised_info_obsolete;    /**< DVR playback disguised obsolete information, take into account for timeshift*/
 } DVR_WrapperPlaybackStatus_t;
 
 typedef struct {
@@ -81,17 +82,18 @@
   DVR_CryptoFunction_t  crypto_fn;                       /**< Crypto callback function.*/
   void                  *crypto_data;                    /**< User data of crypto function.*/
   uint8_t               *clearkey;                       /**< key for encrypted PVR on FTA.*/
-  uint8_t               *cleariv;                        /**< iv for encrpted PVR on FTA.*/
+  uint8_t               *cleariv;                        /**< iv for encrypted PVR on FTA.*/
   uint32_t              keylen;                          /**< key/iv length.*/
   DVR_RecordEventFunction_t   event_fn;                  /**< DVR record event callback function.*/
   void                        *event_userdata;           /**< DVR event userdata.*/
   int                   flush_size;                      /**< DVR flush size.*/
   int                   ringbuf_size;                    /**< DVR ringbuf size.*/
+  DVR_Bool_t            force_sysclock;                  /**< If ture, force to use system clock as PVR index time source. If false, libdvr can determine index time source based on actual situation*/
 } DVR_WrapperRecordOpenParams_t;
 
 typedef struct {
   DVR_WrapperPidsInfo_t pids_info;
-  int                   save_rec_file;                    /**< save rec file with same location,defaule is 0.*/
+  int                   save_rec_file;                    /**< save rec file with same location,default is 0.*/
 } DVR_WrapperRecordStartParams_t;
 
 typedef struct {
@@ -110,7 +112,7 @@
   DVR_CryptoFunction_t    crypto_fn;                       /**< Crypto function.*/
   void                    *crypto_data;                    /**< Crypto function's user data.*/
   uint8_t                 *clearkey;                       /**< key for encrypted PVR on FTA.*/
-  uint8_t                 *cleariv;                        /**< iv for encrpted PVR on FTA.*/
+  uint8_t                 *cleariv;                        /**< iv for encrypted PVR on FTA.*/
   uint32_t                keylen;                          /**< key/iv length.*/
   DVR_PlaybackEventFunction_t  event_fn;                   /**< playback event callback function*/
   void                        *event_userdata;             /**< event userdata*/
@@ -355,7 +357,59 @@
  */
 int dvr_wrapper_segment_get_info_by_location (const char *location, DVR_WrapperInfo_t *p_info);
 
+/**
+ * Stop timeshift.
+ * \param playback The playback handle.
+ * \retval DVR_SUCCESS On success.
+ * \return Error code.
+ */
+int dvr_wrapper_stop_timeshift (DVR_WrapperPlayback_t playback);
+/**
+ * reStart timeshift.
+ * \param playback The playback handle.
+ * \param flags Playback flags.
+ * \param p_pids playback pids info
+ * \retval DVR_SUCCESS On success.
+ * \return Error code.
+ */
+int dvr_wrapper_restart_timeshift(DVR_WrapperPlayback_t playback, DVR_PlaybackFlag_t flags, DVR_PlaybackPids_t *p_pids);
 
+/**
+ * Set log level
+ * \param level Log level, 0: UNKNOWN, 1: DEFAULT, 2:VERBOSE, 3:DEBUG.
+ *                         4: INFO, 5: WARN, 6: ERROR, 7: FATAL
+ * \retval DVR_SUCCESS On success.
+ * \return Error code.
+ */
+int dvr_wrapper_set_log_level (int level);
+
+/**
+ * Set AC4 audio preselection id for playback
+ * \param playback The playback handle.
+ * \param presel_id AC4 audio preselection id
+ * \retval DVR_SUCCESS On success.
+ * \return Error code.
+ */
+int dvr_wrapper_set_ac4_preselection_id(DVR_WrapperPlayback_t playback, int presel_id);
+
+/**
+ * Set various libdvr properties
+ * \param[in] prop_name property name
+ * \param[in] prop_value property value
+ * \retval DVR_SUCCESS On success.
+ * \return DVR_FAILURE On failure.
+ */
+int dvr_wrapper_property_set(const char* prop_name, const char* prop_value);
+
+/**
+ * Get various libdvr properties
+ * \param[in] prop_name property name
+ * \param[out] prop_value property value. Buffer lifecycle is managed by caller.
+ * \param[in] length buffer length of prop_value
+ * \retval DVR_SUCCESS On success.
+ * \return DVR_FAILURE On failure.
+ */
+int dvr_wrapper_property_get(const char* prop_name, char* prop_value, int length);
 
 #ifdef __cplusplus
 }
diff --git a/include/frontend.h b/include/frontend.h
index 544dd16..457133b 100644
--- a/include/frontend.h
+++ b/include/frontend.h
@@ -2,10 +2,10 @@
  * frontend.h
  *
  * Copyright (C) 2000 Marcus Metzler <marcus@convergence.de>
- *		    Ralph  Metzler <ralph@convergence.de>
- *		    Holger Waechtler <holger@convergence.de>
- *		    Andre Draszik <ad@convergence.de>
- *		    for convergence integrated media GmbH
+ *            Ralph  Metzler <ralph@convergence.de>
+ *            Holger Waechtler <holger@convergence.de>
+ *            Andre Draszik <ad@convergence.de>
+ *            for convergence integrated media GmbH
  *
  * This program is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public License
@@ -33,67 +33,67 @@
 #endif
 
 enum fe_type {
-	FE_QPSK,
-	FE_QAM,
-	FE_OFDM,
-	FE_ATSC,
+    FE_QPSK,
+    FE_QAM,
+    FE_OFDM,
+    FE_ATSC,
 #ifdef CONFIG_AMLOGIC_DVB_COMPAT
-	FE_ANALOG,
-	FE_DTMB,
-	FE_ISDBT
+    FE_ANALOG,
+    FE_DTMB,
+    FE_ISDBT
 #endif
 };
 
 enum fe_caps {
-	FE_IS_STUPID			= 0,
-	FE_CAN_INVERSION_AUTO	= 0x1,
-	FE_CAN_FEC_1_2			= 0x2,
-	FE_CAN_FEC_2_3			= 0x4,
-	FE_CAN_FEC_3_4			= 0x8,
-	FE_CAN_FEC_4_5			= 0x10,
-	FE_CAN_FEC_5_6			= 0x20,
-	FE_CAN_FEC_6_7			= 0x40,
-	FE_CAN_FEC_7_8			= 0x80,
-	FE_CAN_FEC_8_9			= 0x100,
-	FE_CAN_FEC_AUTO			= 0x200,
-	FE_CAN_QPSK			= 0x400,
-	FE_CAN_QAM_16			= 0x800,
-	FE_CAN_QAM_32			= 0x1000,
-	FE_CAN_QAM_64			= 0x2000,
-	FE_CAN_QAM_128			= 0x4000,
-	FE_CAN_QAM_256			= 0x8000,
-	FE_CAN_QAM_AUTO			= 0x10000,
-	FE_CAN_TRANSMISSION_MODE_AUTO	= 0x20000,
-	FE_CAN_BANDWIDTH_AUTO		= 0x40000,
-	FE_CAN_GUARD_INTERVAL_AUTO	= 0x80000,
-	FE_CAN_HIERARCHY_AUTO		= 0x100000,
-	FE_CAN_8VSB			= 0x200000,
-	FE_CAN_16VSB			= 0x400000,
+    FE_IS_STUPID            = 0,
+    FE_CAN_INVERSION_AUTO    = 0x1,
+    FE_CAN_FEC_1_2            = 0x2,
+    FE_CAN_FEC_2_3            = 0x4,
+    FE_CAN_FEC_3_4            = 0x8,
+    FE_CAN_FEC_4_5            = 0x10,
+    FE_CAN_FEC_5_6            = 0x20,
+    FE_CAN_FEC_6_7            = 0x40,
+    FE_CAN_FEC_7_8            = 0x80,
+    FE_CAN_FEC_8_9            = 0x100,
+    FE_CAN_FEC_AUTO            = 0x200,
+    FE_CAN_QPSK            = 0x400,
+    FE_CAN_QAM_16            = 0x800,
+    FE_CAN_QAM_32            = 0x1000,
+    FE_CAN_QAM_64            = 0x2000,
+    FE_CAN_QAM_128            = 0x4000,
+    FE_CAN_QAM_256            = 0x8000,
+    FE_CAN_QAM_AUTO            = 0x10000,
+    FE_CAN_TRANSMISSION_MODE_AUTO    = 0x20000,
+    FE_CAN_BANDWIDTH_AUTO        = 0x40000,
+    FE_CAN_GUARD_INTERVAL_AUTO    = 0x80000,
+    FE_CAN_HIERARCHY_AUTO        = 0x100000,
+    FE_CAN_8VSB            = 0x200000,
+    FE_CAN_16VSB            = 0x400000,
 /* We need more bitspace for newer APIs, indicate this. */
-	FE_HAS_EXTENDED_CAPS	        = 0x800000,
-	FE_CAN_MULTISTREAM		= 0x4000000,  /* frontend supports multistream filtering */
-	FE_CAN_TURBO_FEC		= 0x8000000,  /* frontend supports "turbo fec modulation" */
+    FE_HAS_EXTENDED_CAPS            = 0x800000,
+    FE_CAN_MULTISTREAM        = 0x4000000,  /* frontend supports multistream filtering */
+    FE_CAN_TURBO_FEC        = 0x8000000,  /* frontend supports "turbo fec modulation" */
 /* frontend supports "2nd generation modulation" (DVB-S2) */
-	FE_CAN_2G_MODULATION	        = 0x10000000,
-	FE_NEEDS_BENDING		= 0x20000000, /* not supported anymore, don't use (frontend requires frequency bending) */
-	FE_CAN_RECOVER			= 0x40000000, /* frontend can recover from a cable unplug automatically */
-	FE_CAN_MUTE_TS			= 0x80000000  /* frontend can stop spurious TS data output */
+    FE_CAN_2G_MODULATION            = 0x10000000,
+    FE_NEEDS_BENDING        = 0x20000000, /* not supported anymore, don't use (frontend requires frequency bending) */
+    FE_CAN_RECOVER            = 0x40000000, /* frontend can recover from a cable unplug automatically */
+    FE_CAN_MUTE_TS            = 0x80000000  /* frontend can stop spurious TS data output */
 };
 #ifdef CONFIG_AMLOGIC_DVB_COMPAT
 #define FE_CAN_3_LAYER FE_CAN_MULTISTREAM
 #endif
 struct dvb_frontend_info {
-	char       name[128];
-	enum fe_type type;	/* DEPRECATED. Use DTV_ENUM_DELSYS instead */
-	__u32      frequency_min;
-	__u32      frequency_max;
-	__u32      frequency_stepsize;
-	__u32      frequency_tolerance;
-	__u32      symbol_rate_min;
-	__u32      symbol_rate_max;
-	__u32      symbol_rate_tolerance;	/* ppm */
-	__u32      notifier_delay;		/* DEPRECATED */
-	enum fe_caps caps;
+    char       name[128];
+    enum fe_type type;    /* DEPRECATED. Use DTV_ENUM_DELSYS instead */
+    __u32      frequency_min;
+    __u32      frequency_max;
+    __u32      frequency_stepsize;
+    __u32      frequency_tolerance;
+    __u32      symbol_rate_min;
+    __u32      symbol_rate_max;
+    __u32      symbol_rate_tolerance;    /* ppm */
+    __u32      notifier_delay;        /* DEPRECATED */
+    enum fe_caps caps;
 };
 
 
@@ -102,251 +102,251 @@
  *  the meaning of this struct...
  */
 struct dvb_diseqc_master_cmd {
-	__u8 msg [6];	/*  { framing, address, command, data [3] } */
-	__u8 msg_len;	/*  valid values are 3...6  */
+    __u8 msg [6];    /*  { framing, address, command, data [3] } */
+    __u8 msg_len;    /*  valid values are 3...6  */
 };
 
 struct dvb_diseqc_slave_reply {
-	__u8 msg [4];	/*  { framing, data [3] } */
-	__u8 msg_len;	/*  valid values are 0...4, 0 means no msg  */
-	int  timeout;	/*  return from ioctl after timeout ms with */
-};			/*  errorcode when no message was received  */
+    __u8 msg [4];    /*  { framing, data [3] } */
+    __u8 msg_len;    /*  valid values are 0...4, 0 means no msg  */
+    int  timeout;    /*  return from ioctl after timeout ms with */
+};            /*  errorcode when no message was received  */
 
 enum fe_sec_voltage {
-	SEC_VOLTAGE_13,
-	SEC_VOLTAGE_18,
-	SEC_VOLTAGE_OFF,
+    SEC_VOLTAGE_13,
+    SEC_VOLTAGE_18,
+    SEC_VOLTAGE_OFF,
 };
 
 enum fe_sec_tone_mode {
-	SEC_TONE_ON,
-	SEC_TONE_OFF
+    SEC_TONE_ON,
+    SEC_TONE_OFF
 };
 
 enum fe_sec_mini_cmd {
-	SEC_MINI_A,
-	SEC_MINI_B
+    SEC_MINI_A,
+    SEC_MINI_B
 };
 
 /**
  * enum fe_status - enumerates the possible frontend status
- * @FE_HAS_SIGNAL:	found something above the noise level
- * @FE_HAS_CARRIER:	found a DVB signal
- * @FE_HAS_VITERBI:	FEC is stable
- * @FE_HAS_SYNC:	found sync bytes
- * @FE_HAS_LOCK:	everything's working
- * @FE_TIMEDOUT:	no lock within the last ~2 seconds
- * @FE_REINIT:		frontend was reinitialized, application is recommended
- *			to reset DiSEqC, tone and parameters
+ * @FE_HAS_SIGNAL:    found something above the noise level
+ * @FE_HAS_CARRIER:    found a DVB signal
+ * @FE_HAS_VITERBI:    FEC is stable
+ * @FE_HAS_SYNC:    found sync bytes
+ * @FE_HAS_LOCK:    everything's working
+ * @FE_TIMEDOUT:    no lock within the last ~2 seconds
+ * @FE_REINIT:        frontend was reinitialized, application is recommended
+ *            to reset DiSEqC, tone and parameters
  */
 enum fe_status {
-	FE_HAS_SIGNAL	= 0x01,   /* found something above the noise level */
-	FE_HAS_CARRIER	= 0x02,   /* found a DVB signal  */
-	FE_HAS_VITERBI	= 0x04,   /* FEC is stable  */
-	FE_HAS_SYNC	= 0x08,   /* found sync bytes  */
-	FE_HAS_LOCK	= 0x10,   /* everything's working... */
-	FE_TIMEDOUT	= 0x20,   /* no lock within the last ~2 seconds */
-	FE_REINIT	= 0x40,    /* frontend was reinitialized,  */
+    FE_HAS_SIGNAL    = 0x01,   /* found something above the noise level */
+    FE_HAS_CARRIER    = 0x02,   /* found a DVB signal  */
+    FE_HAS_VITERBI    = 0x04,   /* FEC is stable  */
+    FE_HAS_SYNC    = 0x08,   /* found sync bytes  */
+    FE_HAS_LOCK    = 0x10,   /* everything's working... */
+    FE_TIMEDOUT    = 0x20,   /* no lock within the last ~2 seconds */
+    FE_REINIT    = 0x40,    /* frontend was reinitialized,  */
 #ifdef CONFIG_AMLOGIC_DVB_COMPAT
-	BLINDSCAN_NONEDO = 0x80, /* not blind scan  */
-	BLINDSCAN_UPDATESTARTFREQ = 0x100, /* blind scan update start freq  */
-	BLINDSCAN_UPDATEPROCESS   = 0x200, /* blind scan update process  */
-	BLINDSCAN_UPDATERESULTFREQ = 0x400/* blind scan update result  */
+    BLINDSCAN_NONEDO = 0x80, /* not blind scan  */
+    BLINDSCAN_UPDATESTARTFREQ = 0x100, /* blind scan update start freq  */
+    BLINDSCAN_UPDATEPROCESS   = 0x200, /* blind scan update process  */
+    BLINDSCAN_UPDATERESULTFREQ = 0x400/* blind scan update result  */
 #endif
 }; /* application is recommended to reset */
 /* DiSEqC, tone and parameters */
 
 enum fe_spectral_inversion {
-	INVERSION_OFF,
-	INVERSION_ON,
-	INVERSION_AUTO
+    INVERSION_OFF,
+    INVERSION_ON,
+    INVERSION_AUTO
 };
 
 enum fe_code_rate {
-	FEC_NONE = 0,
-	FEC_1_2,
-	FEC_2_3,
-	FEC_3_4,
-	FEC_4_5,
-	FEC_5_6,
-	FEC_6_7,
-	FEC_7_8,
-	FEC_8_9,
-	FEC_AUTO,
-	FEC_3_5,
-	FEC_9_10,
-	FEC_2_5,
+    FEC_NONE = 0,
+    FEC_1_2,
+    FEC_2_3,
+    FEC_3_4,
+    FEC_4_5,
+    FEC_5_6,
+    FEC_6_7,
+    FEC_7_8,
+    FEC_8_9,
+    FEC_AUTO,
+    FEC_3_5,
+    FEC_9_10,
+    FEC_2_5,
 };
 
 enum fe_modulation {
-	QPSK,
-	QAM_16,
-	QAM_32,
-	QAM_64,
-	QAM_128,
-	QAM_256,
-	QAM_AUTO,
-	VSB_8,
-	VSB_16,
-	PSK_8,
-	APSK_16,
-	APSK_32,
-	DQPSK,
-	QAM_4_NR,
+    QPSK,
+    QAM_16,
+    QAM_32,
+    QAM_64,
+    QAM_128,
+    QAM_256,
+    QAM_AUTO,
+    VSB_8,
+    VSB_16,
+    PSK_8,
+    APSK_16,
+    APSK_32,
+    DQPSK,
+    QAM_4_NR,
 };
 
 enum fe_transmit_mode {
-	TRANSMISSION_MODE_2K,
-	TRANSMISSION_MODE_8K,
-	TRANSMISSION_MODE_AUTO,
-	TRANSMISSION_MODE_4K,
-	TRANSMISSION_MODE_1K,
-	TRANSMISSION_MODE_16K,
-	TRANSMISSION_MODE_32K,
-	TRANSMISSION_MODE_C1,
-	TRANSMISSION_MODE_C3780,
+    TRANSMISSION_MODE_2K,
+    TRANSMISSION_MODE_8K,
+    TRANSMISSION_MODE_AUTO,
+    TRANSMISSION_MODE_4K,
+    TRANSMISSION_MODE_1K,
+    TRANSMISSION_MODE_16K,
+    TRANSMISSION_MODE_32K,
+    TRANSMISSION_MODE_C1,
+    TRANSMISSION_MODE_C3780,
 };
 
 enum fe_guard_interval {
-	GUARD_INTERVAL_1_32,
-	GUARD_INTERVAL_1_16,
-	GUARD_INTERVAL_1_8,
-	GUARD_INTERVAL_1_4,
-	GUARD_INTERVAL_AUTO,
-	GUARD_INTERVAL_1_128,
-	GUARD_INTERVAL_19_128,
-	GUARD_INTERVAL_19_256,
-	GUARD_INTERVAL_PN420,
-	GUARD_INTERVAL_PN595,
-	GUARD_INTERVAL_PN945,
+    GUARD_INTERVAL_1_32,
+    GUARD_INTERVAL_1_16,
+    GUARD_INTERVAL_1_8,
+    GUARD_INTERVAL_1_4,
+    GUARD_INTERVAL_AUTO,
+    GUARD_INTERVAL_1_128,
+    GUARD_INTERVAL_19_128,
+    GUARD_INTERVAL_19_256,
+    GUARD_INTERVAL_PN420,
+    GUARD_INTERVAL_PN595,
+    GUARD_INTERVAL_PN945,
 };
 
 enum fe_hierarchy {
-	HIERARCHY_NONE,
-	HIERARCHY_1,
-	HIERARCHY_2,
-	HIERARCHY_4,
-	HIERARCHY_AUTO
+    HIERARCHY_NONE,
+    HIERARCHY_1,
+    HIERARCHY_2,
+    HIERARCHY_4,
+    HIERARCHY_AUTO
 };
 
 enum fe_interleaving {
-	INTERLEAVING_NONE,
-	INTERLEAVING_AUTO,
-	INTERLEAVING_240,
-	INTERLEAVING_720,
+    INTERLEAVING_NONE,
+    INTERLEAVING_AUTO,
+    INTERLEAVING_240,
+    INTERLEAVING_720,
 };
 
 #ifdef CONFIG_AMLOGIC_DVB_COMPAT
 struct fe_blind_scan_parameters {
-	/* minimum tuner frequency in kHz */
-	__u32 min_frequency;
-	/* maximum tuner frequency in kHz */
-	__u32 max_frequency;
-	/* minimum symbol rate in sym/sec */
-	__u32 min_symbol_rate;
-	/* maximum symbol rate in sym/sec */
-	__u32 max_symbol_rate;
-	/* search range in kHz. freq -/+freqRange will be searched */
-	__u32 frequency_range;
-	/* tuner step frequency in kHz */
-	__u32 frequency_step;
-	/* blindscan event timeout */
-	__s32 timeout;
+    /* minimum tuner frequency in kHz */
+    __u32 min_frequency;
+    /* maximum tuner frequency in kHz */
+    __u32 max_frequency;
+    /* minimum symbol rate in sym/sec */
+    __u32 min_symbol_rate;
+    /* maximum symbol rate in sym/sec */
+    __u32 max_symbol_rate;
+    /* search range in kHz. freq -/+freqRange will be searched */
+    __u32 frequency_range;
+    /* tuner step frequency in kHz */
+    __u32 frequency_step;
+    /* blindscan event timeout */
+    __s32 timeout;
 };
 #endif
 
 /* S2API Commands */
-#define DTV_UNDEFINED		0
-#define DTV_TUNE		1
-#define DTV_CLEAR		2
-#define DTV_FREQUENCY		3
-#define DTV_MODULATION		4
-#define DTV_BANDWIDTH_HZ	5
-#define DTV_INVERSION		6
-#define DTV_DISEQC_MASTER	7
-#define DTV_SYMBOL_RATE		8
-#define DTV_INNER_FEC		9
-#define DTV_VOLTAGE		10
-#define DTV_TONE		11
-#define DTV_PILOT		12
-#define DTV_ROLLOFF		13
-#define DTV_DISEQC_SLAVE_REPLY	14
+#define DTV_UNDEFINED        0
+#define DTV_TUNE        1
+#define DTV_CLEAR        2
+#define DTV_FREQUENCY        3
+#define DTV_MODULATION        4
+#define DTV_BANDWIDTH_HZ    5
+#define DTV_INVERSION        6
+#define DTV_DISEQC_MASTER    7
+#define DTV_SYMBOL_RATE        8
+#define DTV_INNER_FEC        9
+#define DTV_VOLTAGE        10
+#define DTV_TONE        11
+#define DTV_PILOT        12
+#define DTV_ROLLOFF        13
+#define DTV_DISEQC_SLAVE_REPLY    14
 
 /* Basic enumeration set for querying unlimited capabilities */
-#define DTV_FE_CAPABILITY_COUNT	15
-#define DTV_FE_CAPABILITY	16
-#define DTV_DELIVERY_SYSTEM	17
+#define DTV_FE_CAPABILITY_COUNT    15
+#define DTV_FE_CAPABILITY    16
+#define DTV_DELIVERY_SYSTEM    17
 
 /* ISDB-T and ISDB-Tsb */
-#define DTV_ISDBT_PARTIAL_RECEPTION	18
-#define DTV_ISDBT_SOUND_BROADCASTING	19
+#define DTV_ISDBT_PARTIAL_RECEPTION    18
+#define DTV_ISDBT_SOUND_BROADCASTING    19
 
-#define DTV_ISDBT_SB_SUBCHANNEL_ID	20
-#define DTV_ISDBT_SB_SEGMENT_IDX	21
-#define DTV_ISDBT_SB_SEGMENT_COUNT	22
+#define DTV_ISDBT_SB_SUBCHANNEL_ID    20
+#define DTV_ISDBT_SB_SEGMENT_IDX    21
+#define DTV_ISDBT_SB_SEGMENT_COUNT    22
 
-#define DTV_ISDBT_LAYERA_FEC			23
-#define DTV_ISDBT_LAYERA_MODULATION		24
-#define DTV_ISDBT_LAYERA_SEGMENT_COUNT		25
-#define DTV_ISDBT_LAYERA_TIME_INTERLEAVING	26
+#define DTV_ISDBT_LAYERA_FEC            23
+#define DTV_ISDBT_LAYERA_MODULATION        24
+#define DTV_ISDBT_LAYERA_SEGMENT_COUNT        25
+#define DTV_ISDBT_LAYERA_TIME_INTERLEAVING    26
 
-#define DTV_ISDBT_LAYERB_FEC			27
-#define DTV_ISDBT_LAYERB_MODULATION		28
-#define DTV_ISDBT_LAYERB_SEGMENT_COUNT		29
-#define DTV_ISDBT_LAYERB_TIME_INTERLEAVING	30
+#define DTV_ISDBT_LAYERB_FEC            27
+#define DTV_ISDBT_LAYERB_MODULATION        28
+#define DTV_ISDBT_LAYERB_SEGMENT_COUNT        29
+#define DTV_ISDBT_LAYERB_TIME_INTERLEAVING    30
 
-#define DTV_ISDBT_LAYERC_FEC			31
-#define DTV_ISDBT_LAYERC_MODULATION		32
-#define DTV_ISDBT_LAYERC_SEGMENT_COUNT		33
-#define DTV_ISDBT_LAYERC_TIME_INTERLEAVING	34
+#define DTV_ISDBT_LAYERC_FEC            31
+#define DTV_ISDBT_LAYERC_MODULATION        32
+#define DTV_ISDBT_LAYERC_SEGMENT_COUNT        33
+#define DTV_ISDBT_LAYERC_TIME_INTERLEAVING    34
 
-#define DTV_API_VERSION		35
+#define DTV_API_VERSION        35
 
-#define DTV_CODE_RATE_HP	36
-#define DTV_CODE_RATE_LP	37
-#define DTV_GUARD_INTERVAL	38
-#define DTV_TRANSMISSION_MODE	39
-#define DTV_HIERARCHY		40
+#define DTV_CODE_RATE_HP    36
+#define DTV_CODE_RATE_LP    37
+#define DTV_GUARD_INTERVAL    38
+#define DTV_TRANSMISSION_MODE    39
+#define DTV_HIERARCHY        40
 
-#define DTV_ISDBT_LAYER_ENABLED	41
+#define DTV_ISDBT_LAYER_ENABLED    41
 
-#define DTV_STREAM_ID		42
-#define DTV_ISDBS_TS_ID_LEGACY	DTV_STREAM_ID
-#define DTV_DVBT2_PLP_ID_LEGACY	43
+#define DTV_STREAM_ID        42
+#define DTV_ISDBS_TS_ID_LEGACY    DTV_STREAM_ID
+#define DTV_DVBT2_PLP_ID_LEGACY    43
 
-#define DTV_ENUM_DELSYS		44
+#define DTV_ENUM_DELSYS        44
 #ifdef CONFIG_AMLOGIC_DVB_COMPAT
 #define DTV_DVBT2_PLP_ID    DTV_DVBT2_PLP_ID_LEGACY
 #endif
 /* ATSC-MH */
-#define DTV_ATSCMH_FIC_VER		45
-#define DTV_ATSCMH_PARADE_ID		46
-#define DTV_ATSCMH_NOG			47
-#define DTV_ATSCMH_TNOG			48
-#define DTV_ATSCMH_SGN			49
-#define DTV_ATSCMH_PRC			50
-#define DTV_ATSCMH_RS_FRAME_MODE	51
-#define DTV_ATSCMH_RS_FRAME_ENSEMBLE	52
-#define DTV_ATSCMH_RS_CODE_MODE_PRI	53
-#define DTV_ATSCMH_RS_CODE_MODE_SEC	54
-#define DTV_ATSCMH_SCCC_BLOCK_MODE	55
-#define DTV_ATSCMH_SCCC_CODE_MODE_A	56
-#define DTV_ATSCMH_SCCC_CODE_MODE_B	57
-#define DTV_ATSCMH_SCCC_CODE_MODE_C	58
-#define DTV_ATSCMH_SCCC_CODE_MODE_D	59
+#define DTV_ATSCMH_FIC_VER        45
+#define DTV_ATSCMH_PARADE_ID        46
+#define DTV_ATSCMH_NOG            47
+#define DTV_ATSCMH_TNOG            48
+#define DTV_ATSCMH_SGN            49
+#define DTV_ATSCMH_PRC            50
+#define DTV_ATSCMH_RS_FRAME_MODE    51
+#define DTV_ATSCMH_RS_FRAME_ENSEMBLE    52
+#define DTV_ATSCMH_RS_CODE_MODE_PRI    53
+#define DTV_ATSCMH_RS_CODE_MODE_SEC    54
+#define DTV_ATSCMH_SCCC_BLOCK_MODE    55
+#define DTV_ATSCMH_SCCC_CODE_MODE_A    56
+#define DTV_ATSCMH_SCCC_CODE_MODE_B    57
+#define DTV_ATSCMH_SCCC_CODE_MODE_C    58
+#define DTV_ATSCMH_SCCC_CODE_MODE_D    59
 
-#define DTV_INTERLEAVING			60
-#define DTV_LNA					61
+#define DTV_INTERLEAVING            60
+#define DTV_LNA                    61
 
 /* Quality parameters */
-#define DTV_STAT_SIGNAL_STRENGTH	62
-#define DTV_STAT_CNR			63
-#define DTV_STAT_PRE_ERROR_BIT_COUNT	64
-#define DTV_STAT_PRE_TOTAL_BIT_COUNT	65
-#define DTV_STAT_POST_ERROR_BIT_COUNT	66
-#define DTV_STAT_POST_TOTAL_BIT_COUNT	67
-#define DTV_STAT_ERROR_BLOCK_COUNT	68
-#define DTV_STAT_TOTAL_BLOCK_COUNT	69
+#define DTV_STAT_SIGNAL_STRENGTH    62
+#define DTV_STAT_CNR            63
+#define DTV_STAT_PRE_ERROR_BIT_COUNT    64
+#define DTV_STAT_PRE_TOTAL_BIT_COUNT    65
+#define DTV_STAT_POST_ERROR_BIT_COUNT    66
+#define DTV_STAT_POST_TOTAL_BIT_COUNT    67
+#define DTV_STAT_ERROR_BLOCK_COUNT    68
+#define DTV_STAT_TOTAL_BLOCK_COUNT    69
 
 #ifdef CONFIG_AMLOGIC_DVB_COMPAT
 
@@ -362,130 +362,136 @@
 #define DTV_BLIND_SCAN_FRE_RANGE        107
 #define DTV_BLIND_SCAN_FRE_STEP         108
 #define DTV_BLIND_SCAN_TIMEOUT          109
+#define DTV_SINGLE_CABLE_VER            110
+#define DTV_SINGLE_CABLE_USER_BAND      111
+#define DTV_SINGLE_CABLE_BAND_FRE       112
+#define DTV_SINGLE_CABLE_BANK           113
+#define DTV_SINGLE_CABLE_UNCOMMITTED    114
+#define DTV_SINGLE_CABLE_COMMITTED      115
 /* Blind scan end*/
-#define DTV_DELIVERY_SUB_SYSTEM			110
-#define DTV_MAX_COMMAND		DTV_DELIVERY_SUB_SYSTEM
+#define DTV_DELIVERY_SUB_SYSTEM            116
+#define DTV_MAX_COMMAND        DTV_DELIVERY_SUB_SYSTEM
 
 #else  /*!defined(CONFIG_AMLOGIC_DVB_COMPAT)*/
 
-#define DTV_MAX_COMMAND		DTV_STAT_TOTAL_BLOCK_COUNT
+#define DTV_MAX_COMMAND        DTV_STAT_TOTAL_BLOCK_COUNT
 
 #endif /*CONFIG_AMLOGIC_DVB_COMPAT*/
 
 
 enum fe_pilot {
-	PILOT_ON,
-	PILOT_OFF,
-	PILOT_AUTO,
+    PILOT_ON,
+    PILOT_OFF,
+    PILOT_AUTO,
 };
 
 enum fe_rolloff {
-	ROLLOFF_35, /* Implied value in DVB-S, default for DVB-S2 */
-	ROLLOFF_20,
-	ROLLOFF_25,
-	ROLLOFF_AUTO,
+    ROLLOFF_35, /* Implied value in DVB-S, default for DVB-S2 */
+    ROLLOFF_20,
+    ROLLOFF_25,
+    ROLLOFF_AUTO,
 };
 
 enum fe_delivery_system {
-	SYS_UNDEFINED,
-	SYS_DVBC_ANNEX_A,
-	SYS_DVBC_ANNEX_B,
-	SYS_DVBT,
-	SYS_DSS,
-	SYS_DVBS,
-	SYS_DVBS2,
-	SYS_DVBH,
-	SYS_ISDBT,
-	SYS_ISDBS,
-	SYS_ISDBC,
-	SYS_ATSC,
-	SYS_ATSCMH,
-	SYS_DTMB,
-	SYS_CMMB,
-	SYS_DAB,
-	SYS_DVBT2,
-	SYS_TURBO,
-	SYS_DVBC_ANNEX_C,
+    SYS_UNDEFINED,
+    SYS_DVBC_ANNEX_A,
+    SYS_DVBC_ANNEX_B,
+    SYS_DVBT,
+    SYS_DSS,
+    SYS_DVBS,
+    SYS_DVBS2,
+    SYS_DVBH,
+    SYS_ISDBT,
+    SYS_ISDBS,
+    SYS_ISDBC,
+    SYS_ATSC,
+    SYS_ATSCMH,
+    SYS_DTMB,
+    SYS_CMMB,
+    SYS_DAB,
+    SYS_DVBT2,
+    SYS_TURBO,
+    SYS_DVBC_ANNEX_C,
 #ifdef CONFIG_AMLOGIC_DVB_COMPAT
-	SYS_ANALOG
+    SYS_ANALOG
 #endif
 };
 
 /* backward compatibility */
-#define SYS_DVBC_ANNEX_AC	SYS_DVBC_ANNEX_A
+#define SYS_DVBC_ANNEX_AC    SYS_DVBC_ANNEX_A
 #define SYS_DMBTH SYS_DTMB /* DMB-TH is legacy name, use DTMB instead */
 
 /* ATSC-MH */
 
 enum atscmh_sccc_block_mode {
-	ATSCMH_SCCC_BLK_SEP      = 0,
-	ATSCMH_SCCC_BLK_COMB     = 1,
-	ATSCMH_SCCC_BLK_RES      = 2,
+    ATSCMH_SCCC_BLK_SEP      = 0,
+    ATSCMH_SCCC_BLK_COMB     = 1,
+    ATSCMH_SCCC_BLK_RES      = 2,
 };
 
 enum atscmh_sccc_code_mode {
-	ATSCMH_SCCC_CODE_HLF     = 0,
-	ATSCMH_SCCC_CODE_QTR     = 1,
-	ATSCMH_SCCC_CODE_RES     = 2,
+    ATSCMH_SCCC_CODE_HLF     = 0,
+    ATSCMH_SCCC_CODE_QTR     = 1,
+    ATSCMH_SCCC_CODE_RES     = 2,
 };
 
 enum atscmh_rs_frame_ensemble {
-	ATSCMH_RSFRAME_ENS_PRI   = 0,
-	ATSCMH_RSFRAME_ENS_SEC   = 1,
+    ATSCMH_RSFRAME_ENS_PRI   = 0,
+    ATSCMH_RSFRAME_ENS_SEC   = 1,
 };
 
 enum atscmh_rs_frame_mode {
-	ATSCMH_RSFRAME_PRI_ONLY  = 0,
-	ATSCMH_RSFRAME_PRI_SEC   = 1,
-	ATSCMH_RSFRAME_RES       = 2,
+    ATSCMH_RSFRAME_PRI_ONLY  = 0,
+    ATSCMH_RSFRAME_PRI_SEC   = 1,
+    ATSCMH_RSFRAME_RES       = 2,
 };
 
 enum atscmh_rs_code_mode {
-	ATSCMH_RSCODE_211_187    = 0,
-	ATSCMH_RSCODE_223_187    = 1,
-	ATSCMH_RSCODE_235_187    = 2,
-	ATSCMH_RSCODE_RES        = 3,
+    ATSCMH_RSCODE_211_187    = 0,
+    ATSCMH_RSCODE_223_187    = 1,
+    ATSCMH_RSCODE_235_187    = 2,
+    ATSCMH_RSCODE_RES        = 3,
 };
 
-#define NO_STREAM_ID_FILTER	(~0U)
+#define NO_STREAM_ID_FILTER    (~0U)
 #define LNA_AUTO                (~0U)
 
 struct dtv_cmds_h {
-	char	*name;		/* A display name for debugging purposes */
+    char    *name;        /* A display name for debugging purposes */
 
-	__u32	cmd;		/* A unique ID */
+    __u32    cmd;        /* A unique ID */
 
-	/* Flags */
-	__u32	set:1;		/* Either a set or get property */
-	__u32	buffer:1;	/* Does this property use the buffer? */
-	__u32	reserved:30;	/* Align */
+    /* Flags */
+    __u32    set:1;        /* Either a set or get property */
+    __u32    buffer:1;    /* Does this property use the buffer? */
+    __u32    reserved:30;    /* Align */
 };
 
 /**
  * Scale types for the quality parameters.
  * @FE_SCALE_NOT_AVAILABLE: That QoS measure is not available. That
- *			    could indicate a temporary or a permanent
- *			    condition.
+ *                could indicate a temporary or a permanent
+ *                condition.
  * @FE_SCALE_DECIBEL: The scale is measured in 0.001 dB steps, typically
- *		  used on signal measures.
+ *          used on signal measures.
  * @FE_SCALE_RELATIVE: The scale is a relative percentual measure,
- *			ranging from 0 (0%) to 0xffff (100%).
+ *            ranging from 0 (0%) to 0xffff (100%).
  * @FE_SCALE_COUNTER: The scale counts the occurrence of an event, like
- *			bit error, block error, lapsed time.
+ *            bit error, block error, lapsed time.
  */
 enum fecap_scale_params {
-	FE_SCALE_NOT_AVAILABLE = 0,
-	FE_SCALE_DECIBEL,
-	FE_SCALE_RELATIVE,
-	FE_SCALE_COUNTER
+    FE_SCALE_NOT_AVAILABLE = 0,
+    FE_SCALE_DECIBEL,
+    FE_SCALE_RELATIVE,
+    FE_SCALE_COUNTER
 };
 
 /**
  * struct dtv_stats - Used for reading a DTV status property
  *
- * @value:	value of the measure. Should range from 0 to 0xffff;
- * @scale:	Filled with enum fecap_scale_params - the scale
- *		in usage for that parameter
+ * @value:    value of the measure. Should range from 0 to 0xffff;
+ * @scale:    Filled with enum fecap_scale_params - the scale
+ *        in usage for that parameter
  *
  * For most delivery systems, this will return a single value for each
  * parameter.
@@ -501,96 +507,96 @@
  * st.len should be filled with the latest filled status + 1.
  *
  * In other words, for ISDB, those values should be filled like:
- *	u.st.stat.svalue[0] = global statistics;
- *	u.st.stat.scale[0] = FE_SCALE_DECIBEL;
- *	u.st.stat.value[1] = layer A statistics;
- *	u.st.stat.scale[1] = FE_SCALE_NOT_AVAILABLE (if not available);
- *	u.st.stat.svalue[2] = layer B statistics;
- *	u.st.stat.scale[2] = FE_SCALE_DECIBEL;
- *	u.st.stat.svalue[3] = layer C statistics;
- *	u.st.stat.scale[3] = FE_SCALE_DECIBEL;
- *	u.st.len = 4;
+ *    u.st.stat.svalue[0] = global statistics;
+ *    u.st.stat.scale[0] = FE_SCALE_DECIBEL;
+ *    u.st.stat.value[1] = layer A statistics;
+ *    u.st.stat.scale[1] = FE_SCALE_NOT_AVAILABLE (if not available);
+ *    u.st.stat.svalue[2] = layer B statistics;
+ *    u.st.stat.scale[2] = FE_SCALE_DECIBEL;
+ *    u.st.stat.svalue[3] = layer C statistics;
+ *    u.st.stat.scale[3] = FE_SCALE_DECIBEL;
+ *    u.st.len = 4;
  */
 struct dtv_stats {
-	__u8 scale;	/* enum fecap_scale_params type */
-	union {
-		__u64 uvalue;	/* for counters and relative scales */
-		__s64 svalue;	/* for 0.001 dB measures */
-	};
+    __u8 scale;    /* enum fecap_scale_params type */
+    union {
+        __u64 uvalue;    /* for counters and relative scales */
+        __s64 svalue;    /* for 0.001 dB measures */
+    };
 } __attribute__ ((packed));
 
 
 #define MAX_DTV_STATS   4
 
 struct dtv_fe_stats {
-	__u8 len;
-	struct dtv_stats stat[MAX_DTV_STATS];
+    __u8 len;
+    struct dtv_stats stat[MAX_DTV_STATS];
 } __attribute__ ((packed));
 
 struct dtv_property {
-	__u32 cmd;
-	__u32 reserved[3];
-	union {
-		__u32 data;
-		struct dtv_fe_stats st;
-		struct {
-			__u8 data[32];
-			__u32 len;
-			__u32 reserved1[3];
-			void *reserved2;
-		} buffer;
-	} u;
-	int result;
+    __u32 cmd;
+    __u32 reserved[3];
+    union {
+        __u32 data;
+        struct dtv_fe_stats st;
+        struct {
+            __u8 data[32];
+            __u32 len;
+            __u32 reserved1[3];
+            void *reserved2;
+        } buffer;
+    } u;
+    int result;
 } __attribute__ ((packed));
 
 struct dtv_property_32 {
-	__u32 cmd;
-	__u32 reserved[3];
-	union {
-		__u32 data;
-		struct dtv_fe_stats st;
-		struct {
-			__u8 data[32];
-			__u32 len;
-			__u32 reserved1[3];
-			__u32 reserved2;
-		} buffer;
-	} u;
-	int result;
+    __u32 cmd;
+    __u32 reserved[3];
+    union {
+        __u32 data;
+        struct dtv_fe_stats st;
+        struct {
+            __u8 data[32];
+            __u32 len;
+            __u32 reserved1[3];
+            __u32 reserved2;
+        } buffer;
+    } u;
+    int result;
 } __attribute__ ((packed));
 
 struct dtv_property_64 {
-	__u32 cmd;
-	__u32 reserved[3];
-	union {
-		__u32 data;
-		struct dtv_fe_stats st;
-		struct {
-			__u8 data[32];
-			__u32 len;
-			__u32 reserved1[3];
-			__u64 reserved2;
-		} buffer;
-	} u;
-	int result;
+    __u32 cmd;
+    __u32 reserved[3];
+    union {
+        __u32 data;
+        struct dtv_fe_stats st;
+        struct {
+            __u8 data[32];
+            __u32 len;
+            __u32 reserved1[3];
+            __u64 reserved2;
+        } buffer;
+    } u;
+    int result;
 } __attribute__ ((packed));
 
 /* num of properties cannot exceed DTV_IOCTL_MAX_MSGS per ioctl */
 #define DTV_IOCTL_MAX_MSGS 64
 
 struct dtv_properties {
-	__u32 num;
-	struct dtv_property *props;
+    __u32 num;
+    struct dtv_property *props;
 };
 
 struct dtv_properties_32 {
-	__u32 num;
-	__u32 props;
+    __u32 num;
+    __u32 props;
 };
 
 struct dtv_properties_64 {
-	__u32 num;
-	__u64 props;
+    __u32 num;
+    __u64 props;
 };
 
 #if defined(__DVB_CORE__) || !defined (__KERNEL__)
@@ -602,13 +608,13 @@
  */
 
 enum fe_bandwidth {
-	BANDWIDTH_8_MHZ,
-	BANDWIDTH_7_MHZ,
-	BANDWIDTH_6_MHZ,
-	BANDWIDTH_AUTO,
-	BANDWIDTH_5_MHZ,
-	BANDWIDTH_10_MHZ,
-	BANDWIDTH_1_712_MHZ,
+    BANDWIDTH_8_MHZ,
+    BANDWIDTH_7_MHZ,
+    BANDWIDTH_6_MHZ,
+    BANDWIDTH_AUTO,
+    BANDWIDTH_5_MHZ,
+    BANDWIDTH_10_MHZ,
+    BANDWIDTH_1_712_MHZ,
 };
 
 /* This is needed for legacy userspace support */
@@ -631,119 +637,119 @@
 
 #ifdef CONFIG_AMLOGIC_DVB_COMPAT
 enum fe_ofdm_mode {
-	OFDM_DVBT,
-	OFDM_DVBT2,
+    OFDM_DVBT,
+    OFDM_DVBT2,
 };
 #endif
 
 struct dvb_qpsk_parameters {
-	__u32		symbol_rate;  /* symbol rate in Symbols per second */
-	fe_code_rate_t	fec_inner;    /* forward error correction (see above) */
+    __u32        symbol_rate;  /* symbol rate in Symbols per second */
+    fe_code_rate_t    fec_inner;    /* forward error correction (see above) */
 };
 
 struct dvb_qam_parameters {
-	__u32		symbol_rate; /* symbol rate in Symbols per second */
-	fe_code_rate_t	fec_inner;   /* forward error correction (see above) */
-	fe_modulation_t	modulation;  /* modulation type (see above) */
+    __u32        symbol_rate; /* symbol rate in Symbols per second */
+    fe_code_rate_t    fec_inner;   /* forward error correction (see above) */
+    fe_modulation_t    modulation;  /* modulation type (see above) */
 };
 
 struct dvb_vsb_parameters {
-	fe_modulation_t	modulation;  /* modulation type (see above) */
+    fe_modulation_t    modulation;  /* modulation type (see above) */
 };
 
 struct dvb_ofdm_parameters {
-	fe_bandwidth_t      bandwidth;
-	fe_code_rate_t      code_rate_HP;  /* high priority stream code rate */
-	fe_code_rate_t      code_rate_LP;  /* low priority stream code rate */
-	fe_modulation_t     constellation; /* modulation type (see above) */
-	fe_transmit_mode_t  transmission_mode;
-	fe_guard_interval_t guard_interval;
-	fe_hierarchy_t      hierarchy_information;
+    fe_bandwidth_t      bandwidth;
+    fe_code_rate_t      code_rate_HP;  /* high priority stream code rate */
+    fe_code_rate_t      code_rate_LP;  /* low priority stream code rate */
+    fe_modulation_t     constellation; /* modulation type (see above) */
+    fe_transmit_mode_t  transmission_mode;
+    fe_guard_interval_t guard_interval;
+    fe_hierarchy_t      hierarchy_information;
 };
 
 #ifdef CONFIG_AMLOGIC_DVB_COMPAT
 #define ANALOG_FLAG_ENABLE_AFC                 0X00000001
 #define  ANALOG_FLAG_MANUL_SCAN                0x00000011
 struct dvb_analog_parameters {
-	/*V4L2_TUNER_MODE_MONO,V4L2_TUNER_MODE_STEREO,*/
-	/*V4L2_TUNER_MODE_LANG2,V4L2_TUNER_MODE_SAP,*/
-	/*V4L2_TUNER_MODE_LANG1,V4L2_TUNER_MODE_LANG1_LANG2 */
-	unsigned int audmode;
-	unsigned int soundsys;	/*A2,BTSC,EIAJ,NICAM */
-	v4l2_std_id std;
-	unsigned int flag;
-	unsigned int afc_range;
+    /*V4L2_TUNER_MODE_MONO,V4L2_TUNER_MODE_STEREO,*/
+    /*V4L2_TUNER_MODE_LANG2,V4L2_TUNER_MODE_SAP,*/
+    /*V4L2_TUNER_MODE_LANG1,V4L2_TUNER_MODE_LANG1_LANG2 */
+    unsigned int audmode;
+    unsigned int soundsys;    /*A2,BTSC,EIAJ,NICAM */
+    v4l2_std_id std;
+    unsigned int flag;
+    unsigned int afc_range;
 };
 #endif
 
 struct dvb_frontend_parameters {
-	/* (absolute) frequency in Hz for DVB-C/DVB-T/ATSC */
-	__u32 frequency;
-	/* intermediate frequency in kHz for DVB-S */
-	fe_spectral_inversion_t inversion;
-	union {
-		struct dvb_qpsk_parameters qpsk;	/* DVB-S */
-		struct dvb_qam_parameters  qam;		/* DVB-C */
-		struct dvb_ofdm_parameters ofdm;	/* DVB-T */
-		struct dvb_vsb_parameters vsb;		/* ATSC */
+    /* (absolute) frequency in Hz for DVB-C/DVB-T/ATSC */
+    __u32 frequency;
+    /* intermediate frequency in kHz for DVB-S */
+    fe_spectral_inversion_t inversion;
+    union {
+        struct dvb_qpsk_parameters qpsk;    /* DVB-S */
+        struct dvb_qam_parameters  qam;        /* DVB-C */
+        struct dvb_ofdm_parameters ofdm;    /* DVB-T */
+        struct dvb_vsb_parameters vsb;        /* ATSC */
 #if 0 && defined(CONFIG_AMLOGIC_DVB_COMPAT)
-		struct dvb_analog_parameters analog;
+        struct dvb_analog_parameters analog;
 #endif
-	} u;
+    } u;
 };
 
 #ifdef CONFIG_AMLOGIC_DVB_COMPAT
 
 struct dvb_frontend_parameters_ex {
-	__u32 frequency;  /* (absolute) frequency in Hz for DVB-C/DVB-T/ATSC */
-			  /* intermediate frequency in kHz for DVB-S */
-	fe_spectral_inversion_t inversion;
-	union {
-		struct dvb_qpsk_parameters qpsk;	/* DVB-S */
-		struct dvb_qam_parameters  qam;		/* DVB-C */
-		struct dvb_ofdm_parameters ofdm;	/* DVB-T */
-		struct dvb_vsb_parameters vsb;		/* ATSC */
-		struct dvb_analog_parameters analog;
-		/* Add extenstion data here */
-	} u;
+    __u32 frequency;  /* (absolute) frequency in Hz for DVB-C/DVB-T/ATSC */
+              /* intermediate frequency in kHz for DVB-S */
+    fe_spectral_inversion_t inversion;
+    union {
+        struct dvb_qpsk_parameters qpsk;    /* DVB-S */
+        struct dvb_qam_parameters  qam;        /* DVB-C */
+        struct dvb_ofdm_parameters ofdm;    /* DVB-T */
+        struct dvb_vsb_parameters vsb;        /* ATSC */
+        struct dvb_analog_parameters analog;
+        /* Add extension data here */
+    } u;
 };
 
 /*
 static char dvb_check_frontend_parameters_size[
-	(sizeof(struct dvb_frontend_parameters_ex)
-	== sizeof(struct dvb_frontend_parameters)) ? 1 : -1]
-	__attribute__((__unused__));
+    (sizeof(struct dvb_frontend_parameters_ex)
+    == sizeof(struct dvb_frontend_parameters)) ? 1 : -1]
+    __attribute__((__unused__));
 */
 
 #endif /*CONFIG_AMLOGIC_DVB_COMPAT*/
 
 struct dvb_frontend_event {
-	fe_status_t status;
-	struct dvb_frontend_parameters parameters;
+    fe_status_t status;
+    struct dvb_frontend_parameters parameters;
 };
 #ifdef CONFIG_AMLOGIC_DVB_COMPAT
 /* Satellite blind scan event */
 struct dvbsx_blindscanevent {
-	enum fe_status status;
-	union {
-		/* The percentage completion of the*/
-		/*blind scan procedure. A value of*/
-		/*100 indicates that the blind scan*/
-		/*is finished. */
-		__u16 m_uiprogress;
-		/*The start scan frequency in units of kHz.*/
-		/*The minimum value depends on the tuner*/
-		/*specification.*/
-		__u32 m_uistartfreq_khz;
-		/* Blind scan channel info. */
-		struct dvb_frontend_parameters parameters;
-	} u;
+    enum fe_status status;
+    union {
+        /* The percentage completion of the*/
+        /*blind scan procedure. A value of*/
+        /*100 indicates that the blind scan*/
+        /*is finished. */
+        __u16 m_uiprogress;
+        /*The start scan frequency in units of kHz.*/
+        /*The minimum value depends on the tuner*/
+        /*specification.*/
+        __u32 m_uistartfreq_khz;
+        /* Blind scan channel info. */
+        struct dvb_frontend_parameters parameters;
+    } u;
 };
 #endif /*CONFIG_AMLOGIC_DVB_COMPAT*/
 #endif
 
-#define FE_SET_PROPERTY		   _IOW('o', 82, struct dtv_properties)
-#define FE_GET_PROPERTY		   _IOR('o', 83, struct dtv_properties)
+#define FE_SET_PROPERTY           _IOW('o', 82, struct dtv_properties)
+#define FE_GET_PROPERTY           _IOR('o', 83, struct dtv_properties)
 
 #define FE_SET_PROPERTY_32     _IOW('o', 82, struct dtv_properties_32)
 #define FE_GET_PROPERTY_32     _IOR('o', 83, struct dtv_properties_32)
@@ -754,68 +760,68 @@
 #ifdef CONFIG_AMLOGIC_DVB_COMPAT
 /*for atv*/
 struct tuner_status_s {
-	unsigned int frequency;
-	unsigned int rssi;
-	unsigned char mode;/*dtv:0 or atv:1*/
-	unsigned char tuner_locked;/*notlocked:0,locked:1*/
-	union {
-		void *ressrved;
-		__u64 reserved1;
-	};
+    unsigned int frequency;
+    unsigned int rssi;
+    unsigned char mode;/*dtv:0 or atv:1*/
+    unsigned char tuner_locked;/*notlocked:0,locked:1*/
+    union {
+        void *ressrved;
+        __u64 reserved1;
+    };
 };
 
 
 struct atv_status_s {
-	unsigned char atv_lock;/*notlocked:0,locked 1*/
-	v4l2_std_id	  std;
-	unsigned int  audmode;
-	int  snr;
-	int  afc;
-	union {
-		void *resrvred;
-		__u64 reserved1;
-	};
+    unsigned char atv_lock;/*notlocked:0,locked 1*/
+    v4l2_std_id      std;
+    unsigned int  audmode;
+    int  snr;
+    int  afc;
+    union {
+        void *resrvred;
+        __u64 reserved1;
+    };
 };
 
 struct sound_status_s {
-	unsigned short sound_sys;/*A2DK/A2BG/NICAM BG/NICAM DK/BTSC/EIAJ*/
-	unsigned short sound_mode;/*SETERO/DUAL/MONO/SAP*/
-	union {
-		void *resrvred;
-		__u64 reserved1;
-	};
+    unsigned short sound_sys;/*A2DK/A2BG/NICAM BG/NICAM DK/BTSC/EIAJ*/
+    unsigned short sound_mode;/*SETERO/DUAL/MONO/SAP*/
+    union {
+        void *resrvred;
+        __u64 reserved1;
+    };
 };
 
 
 enum tuner_param_cmd_e {
-	TUNER_CMD_AUDIO_MUTE = 0x0000,
-	TUNER_CMD_AUDIO_ON,
-	TUNER_CMD_TUNER_POWER_ON,
-	TUNER_CMD_TUNER_POWER_DOWN,
-	TUNER_CMD_SET_VOLUME,
-	TUNER_CMD_SET_LEAP_SETP_SIZE,
-	TUNER_CMD_GET_MONO_MODE,
-	TUNER_CMD_SET_BEST_LOCK_RANGE,
-	TUNER_CMD_GET_BEST_LOCK_RANGE,
-	TUNER_CMD_SET_CVBS_AMP_OUT,
-	TUNER_CMD_GET_CVBS_AMP_OUT,
-	TUNER_CMD_NULL,
+    TUNER_CMD_AUDIO_MUTE = 0x0000,
+    TUNER_CMD_AUDIO_ON,
+    TUNER_CMD_TUNER_POWER_ON,
+    TUNER_CMD_TUNER_POWER_DOWN,
+    TUNER_CMD_SET_VOLUME,
+    TUNER_CMD_SET_LEAP_SETP_SIZE,
+    TUNER_CMD_GET_MONO_MODE,
+    TUNER_CMD_SET_BEST_LOCK_RANGE,
+    TUNER_CMD_GET_BEST_LOCK_RANGE,
+    TUNER_CMD_SET_CVBS_AMP_OUT,
+    TUNER_CMD_GET_CVBS_AMP_OUT,
+    TUNER_CMD_NULL,
 };
 
 
 /*parameter for set param box*/
 struct tuner_param_s {
-	enum tuner_param_cmd_e cmd;
-	unsigned int      parm;
-	unsigned int	resvred;
+    enum tuner_param_cmd_e cmd;
+    unsigned int      parm;
+    unsigned int    reserved;
 };
 
 
 enum fe_layer {
-	Layer_A_B_C,
-	Layer_A,
-	Layer_B,
-	Layer_C,
+    Layer_A_B_C,
+    Layer_A,
+    Layer_B,
+    Layer_C,
 };
 
 // typedef struct dvb_analog_parameters dvb_analog_parameters_t;
@@ -830,14 +836,40 @@
 
 /* Satellite blind scan settings */
 struct dvbsx_blindscanpara {
-	__u32 minfrequency;/* minimum tuner frequency in kHz */
-	__u32 maxfrequency;/* maximum tuner frequency in kHz */
-	__u32 minSymbolRate;/* minimum symbol rate in sym/sec */
-	__u32 maxSymbolRate;/* maximum symbol rate in sym/sec */
-	/*search range in kHz. freq -/+freqRange will be searched */
-	__u32 frequencyRange;
-	__u32 frequencyStep;/* tuner step frequency in kHz */
-	__s32 timeout;/* blindscan event timeout*/
+    __u32 minfrequency;/* minimum tuner frequency in kHz */
+    __u32 maxfrequency;/* maximum tuner frequency in kHz */
+    __u32 minSymbolRate;/* minimum symbol rate in sym/sec */
+    __u32 maxSymbolRate;/* maximum symbol rate in sym/sec */
+    /*search range in kHz. freq -/+freqRange will be searched */
+    __u32 frequencyRange;
+    __u32 frequencyStep;/* tuner step frequency in kHz */
+    __s32 timeout;/* blindscan event timeout*/
+};
+
+struct dvbsx_singlecable_parameters {
+	/* not singlecable: 0, 1.0X - 1(EN50494), 2.0X - 2(EN50607) */
+	__u32 version;
+	__u32 userband;  /* 1.0X: 0 - 7, 2.0X: 0 - 31 */
+	__u32 frequency; /* KHz */
+	__u32 bank;
+	/*
+	 * Uncommitted switches setting for SCD2 (Similar to DiSEqC WriteN1 command,
+	 * but lower 4 bits only)
+	 *  Bit[0] : Switch 1 Position A or B
+	 *  Bit[1] : Switch 2 Position A or B
+	 *  Bit[2] : Switch 3 Position A or B
+	 *  Bit[3] : Switch 4 Position A or B
+	 */
+	__u32 uncommitted;
+	/*
+	 * Committed switches setting for SCD2 (Similar to DiSEqC WriteN0 command,
+	 * but lower 4 bits only)
+	 *  Bit[0] : Low or High Band
+	 *  Bit[1] : Vertical or Horizontal Polarization
+	 *  Bit[2] : Satellite Position A or B
+	 *  Bit[3] : Option Switch Position A or B
+	 */
+	__u32 committed;
 };
 #endif /*CONFIG_AMLOGIC_DVB_COMPAT*/
 /**
@@ -849,27 +881,27 @@
  */
 #define FE_TUNE_MODE_ONESHOT 0x01
 
-#define FE_GET_INFO		   _IOR('o', 61, struct dvb_frontend_info)
+#define FE_GET_INFO           _IOR('o', 61, struct dvb_frontend_info)
 
 #define FE_DISEQC_RESET_OVERLOAD   _IO('o', 62)
 #define FE_DISEQC_SEND_MASTER_CMD  _IOW('o', 63, struct dvb_diseqc_master_cmd)
 #define FE_DISEQC_RECV_SLAVE_REPLY _IOR('o', 64, struct dvb_diseqc_slave_reply)
 #define FE_DISEQC_SEND_BURST       _IO('o', 65)  /* fe_sec_mini_cmd_t */
 
-#define FE_SET_TONE		   _IO('o', 66)  /* fe_sec_tone_mode_t */
-#define FE_SET_VOLTAGE		   _IO('o', 67)  /* fe_sec_voltage_t */
+#define FE_SET_TONE           _IO('o', 66)  /* fe_sec_tone_mode_t */
+#define FE_SET_VOLTAGE           _IO('o', 67)  /* fe_sec_voltage_t */
 #define FE_ENABLE_HIGH_LNB_VOLTAGE _IO('o', 68)  /* int */
 
-#define FE_READ_STATUS		   _IOR('o', 69, fe_status_t)
-#define FE_READ_BER		   _IOR('o', 70, __u32)
+#define FE_READ_STATUS           _IOR('o', 69, fe_status_t)
+#define FE_READ_BER           _IOR('o', 70, __u32)
 #define FE_READ_SIGNAL_STRENGTH    _IOR('o', 71, __u16)
-#define FE_READ_SNR		   _IOR('o', 72, __u16)
+#define FE_READ_SNR           _IOR('o', 72, __u16)
 #define FE_READ_UNCORRECTED_BLOCKS _IOR('o', 73, __u32)
 
-#define FE_SET_FRONTEND		   _IOW('o', 76, struct dvb_frontend_parameters)
-#define FE_GET_FRONTEND		   _IOR('o', 77, struct dvb_frontend_parameters)
+#define FE_SET_FRONTEND           _IOW('o', 76, struct dvb_frontend_parameters)
+#define FE_GET_FRONTEND           _IOR('o', 77, struct dvb_frontend_parameters)
 #define FE_SET_FRONTEND_TUNE_MODE  _IO('o', 81) /* unsigned int */
-#define FE_GET_EVENT		   _IOR('o', 78, struct dvb_frontend_event)
+#define FE_GET_EVENT           _IOR('o', 78, struct dvb_frontend_event)
 
 #define FE_DISHNETWORK_SEND_LEGACY_CMD _IO('o', 80) /* unsigned int */
 
diff --git a/include/index_file.h b/include/index_file.h
index 174e113..7f0d084 100644
--- a/include/index_file.h
+++ b/include/index_file.h
@@ -11,7 +11,7 @@
 typedef enum {
   INDEX_RECORD_MODE,
   INDEX_PLAYBACK_MODE,
-  INDEX_UNKNOW_MODE,
+  INDEX_UNKNOWN_MODE,
 } Index_FileOpenMode_t;
 
 typedef struct Index_FileOpenParams_s {
diff --git a/include/list.h b/include/list.h
index e964d8f..7bc982a 100644
--- a/include/list.h
+++ b/include/list.h
@@ -21,14 +21,14 @@
 #ifndef container_of
 /**
  * container_of - cast a member of a structure out to the containing structure
- * @ptr:	the pointer to the member.
- * @type:	the type of the container struct this is embedded in.
- * @member:	the name of the member within the struct.
+ * @ptr:    the pointer to the member.
+ * @type:    the type of the container struct this is embedded in.
+ * @member:    the name of the member within the struct.
  *
  */
-#define container_of(ptr, type, member) ({			\
-	const typeof(((type *)0)->member) * __mptr = (ptr);	\
-	(type *)((char *)__mptr - offsetof(type, member)); })
+#define container_of(ptr, type, member) ({            \
+    const typeof(((type *)0)->member) * __mptr = (ptr);    \
+    (type *)((char *)__mptr - offsetof(type, member)); })
 #endif
 
 #define LIST_POISON1  ((void *) 0x00100100)
@@ -42,86 +42,86 @@
  *
  * Some of the internal functions ("__xxx") are useful when
  * manipulating whole lists rather than single entries, as
- * sometimes we already know the cnext/cprev entries and we can
+ * sometimes we already know the c_next/c_prev entries and we can
  * generate better code by using them directly rather than
  * using the generic single-entry routines.
  */
 
 struct list_head {
-	struct list_head *cnext, *cprev;
+    struct list_head *c_next, *c_prev;
 };
 
 #define LIST_HEAD_INIT(name) { &(name), &(name) }
 
 #define LIST_HEAD(name) \
-	struct list_head name = LIST_HEAD_INIT(name)
+    struct list_head name = LIST_HEAD_INIT(name)
 
 static inline void INIT_LIST_HEAD(struct list_head *list)
 {
-	list->cnext = list;
-	list->cprev = list;
+    list->c_next = list;
+    list->c_prev = list;
 }
 
 /*
- * Insert a cnew entry between two known consecutive entries.
+ * Insert a c_new entry between two known consecutive entries.
  *
  * This is only for internal list manipulation where we know
- * the cprev/cnext entries already!
+ * the c_prev/c_next entries already!
  */
 #ifndef CONFIG_DEBUG_LIST
-static inline void __list_add(struct list_head *cnew,
-			      struct list_head *cprev,
-			      struct list_head *cnext)
+static inline void __list_add(struct list_head *c_new,
+                  struct list_head *c_prev,
+                  struct list_head *c_next)
 {
-	cnext->cprev = cnew;
-	cnew->cnext = cnext;
-	cnew->cprev = cprev;
-	cprev->cnext = cnew;
+    c_next->c_prev = c_new;
+    c_new->c_next = c_next;
+    c_new->c_prev = c_prev;
+    c_prev->c_next = c_new;
 }
 #else
-extern void __list_add(struct list_head *cnew,
-			      struct list_head *prev,
-			      struct list_head *next);
+extern void __list_add(struct list_head *c_new,
+                  struct list_head *prev,
+                  struct list_head *next);
 #endif
 
 /**
- * list_add - add a cnew entry
- * @cnew: cnew entry to be added
+ * list_add - add a c_new entry
+ * @c_new: c_new entry to be added
  * @head: list head to add it after
  *
- * Insert a cnew entry after the specified head.
+ * Insert a c_new entry after the specified head.
  * This is good for implementing stacks.
  */
-static inline void list_add(struct list_head *cnew, struct list_head *head)
+static inline void list_add(struct list_head *c_new, struct list_head *head)
 {
-	__list_add(cnew, head, head->cnext);
+    __list_add((struct list_head*)c_new, head, head->c_next);
 }
 
 
 /**
- * list_add_tail - add a cnew entry
- * @cnew: cnew entry to be added
+ * list_add_tail - add a c_new entry
+ * @c_new: c_new entry to be added
  * @head: list head to add it before
  *
- * Insert a cnew entry before the specified head.
+ * Insert a c_new entry before the specified head.
  * This is useful for implementing queues.
  */
-static inline void list_add_tail(struct list_head *cnew, struct list_head *head)
+static inline void list_add_tail(struct list_head *c_new, struct list_head *head)
 {
-	__list_add(cnew, head->cprev, head);
+    __list_add(c_new, head->c_prev, head);
 }
 
 /*
- * Delete a list entry by making the cprev/cnext entries
+ * Delete a list entry by making the c_prev/c_next entries
  * point to each other.
  *
  * This is only for internal list manipulation where we know
- * the cprev/cnext entries already!
+ * the c_prev/c_next entries already!
  */
-static inline void __list_del(struct list_head * cprev, struct list_head * cnext)
+static inline void __list_del(struct list_head * c_prev, struct list_head * c_next)
 {
-	cnext->cprev = cprev;
-	cprev->cnext = cnext;
+    c_next->c_prev = c_prev;
+    c_prev->c_next = c_next;
 }
 
 /**
@@ -133,35 +133,35 @@
 #ifndef CONFIG_DEBUG_LIST
 static inline void list_del(struct list_head *entry)
 {
-	__list_del(entry->cprev, entry->cnext);
-	entry->cnext = (struct list_head *)LIST_POISON1;
-	entry->cprev = (struct list_head *)LIST_POISON2;
+    __list_del(entry->c_prev, entry->c_next);
+    entry->c_next = (struct list_head *)LIST_POISON1;
+    entry->c_prev = (struct list_head *)LIST_POISON2;
 }
 #else
 extern void list_del(struct list_head *entry);
 #endif
 
 /**
- * list_replace - replace old entry by cnew one
+ * list_replace - replace old entry by c_new one
  * @old : the element to be replaced
- * @cnew : the cnew element to insert
+ * @c_new : the c_new element to insert
  *
  * If @old was empty, it will be overwritten.
  */
 static inline void list_replace(struct list_head *old,
-				struct list_head *cnew)
+                struct list_head *c_new)
 {
-	cnew->cnext = old->cnext;
-	cnew->cnext->cprev = cnew;
-	cnew->cprev = old->cprev;
-	cnew->cprev->cnext = cnew;
+    c_new->c_next = old->c_next;
+    c_new->c_next->c_prev = c_new;
+    c_new->c_prev = old->c_prev;
+    c_new->c_prev->c_next = c_new;
 }
 
 static inline void list_replace_init(struct list_head *old,
-					struct list_head *cnew)
+                    struct list_head *c_new)
 {
-	list_replace(old, cnew);
-	INIT_LIST_HEAD(old);
+    list_replace(old, c_new);
+    INIT_LIST_HEAD(old);
 }
 
 /**
@@ -170,8 +170,8 @@
  */
 static inline void list_del_init(struct list_head *entry)
 {
-	__list_del(entry->cprev, entry->cnext);
-	INIT_LIST_HEAD(entry);
+    __list_del(entry->c_prev, entry->c_next);
+    INIT_LIST_HEAD(entry);
 }
 
 /**
@@ -181,8 +181,8 @@
  */
 static inline void list_move(struct list_head *list, struct list_head *head)
 {
-	__list_del(list->cprev, list->cnext);
-	list_add(list, head);
+    __list_del(list->c_prev, list->c_next);
+    list_add(list, head);
 }
 
 /**
@@ -191,10 +191,10 @@
  * @head: the head that will follow our entry
  */
 static inline void list_move_tail(struct list_head *list,
-				  struct list_head *head)
+                  struct list_head *head)
 {
-	__list_del(list->cprev, list->cnext);
-	list_add_tail(list, head);
+    __list_del(list->c_prev, list->c_next);
+    list_add_tail(list, head);
 }
 
 /**
@@ -203,9 +203,9 @@
  * @head: the head of the list
  */
 static inline int list_is_last(const struct list_head *list,
-				const struct list_head *head)
+                const struct list_head *head)
 {
-	return list->cnext == head;
+    return list->c_next == head;
 }
 
 /**
@@ -214,7 +214,7 @@
  */
 static inline int list_empty(const struct list_head *head)
 {
-	return head->cnext == head;
+    return head->c_next == head;
 }
 
 /**
@@ -223,7 +223,7 @@
  *
  * Description:
  * tests whether a list is empty _and_ checks that no other CPU might be
- * in the process of modifying either member (cnext or cprev)
+ * in the process of modifying either member (c_next or c_prev)
  *
  * NOTE: using list_empty_careful() without synchronization
  * can only be safe if the only activity that can happen
@@ -232,8 +232,8 @@
  */
 static inline int list_empty_careful(const struct list_head *head)
 {
-	struct list_head *cnext = head->cnext;
-	return (cnext == head) && (cnext == head->cprev);
+    struct list_head *c_next = head->c_next;
+    return (c_next == head) && (c_next == head->c_prev);
 }
 
 /**
@@ -242,12 +242,12 @@
  */
 static inline void list_rotate_left(struct list_head *head)
 {
-	struct list_head *first;
+    struct list_head *first;
 
-	if (!list_empty(head)) {
-		first = head->cnext;
-		list_move_tail(first, head);
-	}
+    if (!list_empty(head)) {
+        first = head->c_next;
+        list_move_tail(first, head);
+    }
 }
 
 /**
@@ -256,27 +256,27 @@
  */
 static inline int list_is_singular(const struct list_head *head)
 {
-	return !list_empty(head) && (head->cnext == head->cprev);
+    return !list_empty(head) && (head->c_next == head->c_prev);
 }
 
 static inline void __list_cut_position(struct list_head *list,
-		struct list_head *head, struct list_head *entry)
+        struct list_head *head, struct list_head *entry)
 {
-	struct list_head *cnew_first = entry->cnext;
-	list->cnext = head->cnext;
-	list->cnext->cprev = list;
-	list->cprev = entry;
-	entry->cnext = list;
-	head->cnext = cnew_first;
-	cnew_first->cprev = head;
+    struct list_head *c_new_first = entry->c_next;
+    list->c_next = head->c_next;
+    list->c_next->c_prev = list;
+    list->c_prev = entry;
+    entry->c_next = list;
+    head->c_next = c_new_first;
+    c_new_first->c_prev = head;
 }
 
 /**
  * list_cut_position - cut a list into two
- * @list: a cnew list to add all removed entries
+ * @list: a c_new list to add all removed entries
  * @head: a list with entries
  * @entry: an entry within head, could be the head itself
- *	and if so we won't cut the list
+ *    and if so we won't cut the list
  *
  * This helper moves the initial part of @head, up to and
  * including @entry, from @head to @list. You should
@@ -286,150 +286,150 @@
  *
  */
 static inline void list_cut_position(struct list_head *list,
-		struct list_head *head, struct list_head *entry)
+        struct list_head *head, struct list_head *entry)
 {
-	if (list_empty(head))
-		return;
-	if (list_is_singular(head) &&
-		(head->cnext != entry && head != entry))
-		return;
-	if (entry == head)
-		INIT_LIST_HEAD(list);
-	else
-		__list_cut_position(list, head, entry);
+    if (list_empty(head))
+        return;
+    if (list_is_singular(head) &&
+        (head->c_next != entry && head != entry))
+        return;
+    if (entry == head)
+        INIT_LIST_HEAD(list);
+    else
+        __list_cut_position(list, head, entry);
 }
 
 static inline void __list_splice(const struct list_head *list,
-				 struct list_head *cprev,
-				 struct list_head *cnext)
+                 struct list_head *c_prev,
+                 struct list_head *c_next)
 {
-	struct list_head *first = list->cnext;
-	struct list_head *last = list->cprev;
+    struct list_head *first = list->c_next;
+    struct list_head *last = list->c_prev;
 
-	first->cprev = cprev;
-	cprev->cnext = first;
+    first->c_prev = c_prev;
+    c_prev->c_next = first;
 
-	last->cnext = cnext;
-	cnext->cprev = last;
+    last->c_next = c_next;
+    c_next->c_prev = last;
 }
 
 /**
  * list_splice - join two lists, this is designed for stacks
- * @list: the cnew list to add.
+ * @list: the c_new list to add.
  * @head: the place to add it in the first list.
  */
 static inline void list_splice(const struct list_head *list,
-				struct list_head *head)
+                struct list_head *head)
 {
-	if (!list_empty(list))
-		__list_splice(list, head, head->cnext);
+    if (!list_empty(list))
+        __list_splice(list, head, head->c_next);
 }
 
 /**
  * list_splice_tail - join two lists, each list being a queue
- * @list: the cnew list to add.
+ * @list: the c_new list to add.
  * @head: the place to add it in the first list.
  */
 static inline void list_splice_tail(struct list_head *list,
-				struct list_head *head)
+                struct list_head *head)
 {
-	if (!list_empty(list))
-		__list_splice(list, head->cprev, head);
+    if (!list_empty(list))
+        __list_splice(list, head->c_prev, head);
 }
 
 /**
  * list_splice_init - join two lists and reinitialise the emptied list.
- * @list: the cnew list to add.
+ * @list: the c_new list to add.
  * @head: the place to add it in the first list.
  *
  * The list at @list is reinitialised
  */
 static inline void list_splice_init(struct list_head *list,
-				    struct list_head *head)
+                    struct list_head *head)
 {
-	if (!list_empty(list)) {
-		__list_splice(list, head, head->cnext);
-		INIT_LIST_HEAD(list);
-	}
+    if (!list_empty(list)) {
+        __list_splice(list, head, head->c_next);
+        INIT_LIST_HEAD(list);
+    }
 }
 
 /**
  * list_splice_tail_init - join two lists and reinitialise the emptied list
- * @list: the cnew list to add.
+ * @list: the c_new list to add.
  * @head: the place to add it in the first list.
  *
  * Each of the lists is a queue.
  * The list at @list is reinitialised
  */
 static inline void list_splice_tail_init(struct list_head *list,
-					 struct list_head *head)
+                     struct list_head *head)
 {
-	if (!list_empty(list)) {
-		__list_splice(list, head->cprev, head);
-		INIT_LIST_HEAD(list);
-	}
+    if (!list_empty(list)) {
+        __list_splice(list, head->c_prev, head);
+        INIT_LIST_HEAD(list);
+    }
 }
 
 /**
  * list_entry - get the struct for this entry
- * @ptr:	the &struct list_head pointer.
- * @type:	the type of the struct this is embedded in.
- * @member:	the name of the list_struct within the struct.
+ * @ptr:    the &struct list_head pointer.
+ * @type:    the type of the struct this is embedded in.
+ * @member:    the name of the list_struct within the struct.
  */
 #define list_entry(ptr, type, member) \
-	container_of(ptr, type, member)
+    container_of(ptr, type, member)
 
 /**
  * list_first_entry - get the first element from a list
- * @ptr:	the list head to take the element from.
- * @type:	the type of the struct this is embedded in.
- * @member:	the name of the list_struct within the struct.
+ * @ptr:    the list head to take the element from.
+ * @type:    the type of the struct this is embedded in.
+ * @member:    the name of the list_struct within the struct.
  *
  * Note, that list is expected to be not empty.
  */
 #define list_first_entry(ptr, type, member) \
-	list_entry((ptr)->cnext, type, member)
+    list_entry((ptr)->c_next, type, member)
 
 /**
  * list_last_entry - get the last element from a list
- * @ptr:	the list head to take the element from.
- * @type:	the type of the struct this is embedded in.
- * @member:	the name of the list_head within the struct.
+ * @ptr:    the list head to take the element from.
+ * @type:    the type of the struct this is embedded in.
+ * @member:    the name of the list_head within the struct.
  *
  * Note, that list is expected to be not empty.
  */
 #define list_last_entry(ptr, type, member) \
-	list_entry((ptr)->cprev, type, member)
+    list_entry((ptr)->c_prev, type, member)
 
 /**
- * list_next_entry - get the cnext element in list
- * @pos:	the type * to cursor
- * @member:	the name of the list_head within the struct.
+ * list_next_entry - get the c_next element in list
+ * @pos:    the type * to cursor
+ * @member:    the name of the list_head within the struct.
  */
 #define list_next_entry(pos, member) \
-	list_entry((pos)->member.cnext, typeof(*(pos)), member)
+    list_entry((pos)->member.c_next, typeof(*(pos)), member)
 
 /**
- * list_prev_entry - get the cprev element in list
- * @pos:	the type * to cursor
- * @member:	the name of the list_head within the struct.
+ * list_prev_entry - get the c_prev element in list
+ * @pos:    the type * to cursor
+ * @member:    the name of the list_head within the struct.
  */
 #define list_prev_entry(pos, member) \
-	list_entry((pos)->member.cprev, typeof(*(pos)), member)
+    list_entry((pos)->member.c_prev, typeof(*(pos)), member)
 
 /**
- * list_for_each	-	iterate over a list
- * @pos:	the &struct list_head to use as a loop cursor.
- * @head:	the head for your list.
+ * list_for_each    -    iterate over a list
+ * @pos:    the &struct list_head to use as a loop cursor.
+ * @head:    the head for your list.
  */
 #define list_for_each(pos, head) \
-	for (pos = (head)->cnext; prefetch(pos->cnext), pos != (head); \
-			pos = pos->cnext)
+    for (pos = (head)->c_next; prefetch(pos->c_next), pos != (head); \
+            pos = pos->c_next)
 
 /**
- * __list_for_each	-	iterate over a list
- * @pos:	the &struct list_head to use as a loop cursor.
- * @head:	the head for your list.
+ * __list_for_each    -    iterate over a list
+ * @pos:    the &struct list_head to use as a loop cursor.
+ * @head:    the head for your list.
  *
  * This variant differs from list_for_each() in that it's the
  * simplest possible list iteration code, no prefetching is done.
@@ -437,170 +437,170 @@
  * or 1 entry) most of the time.
  */
 #define __list_for_each(pos, head) \
-	for (pos = (head)->cnext; pos != (head); pos = pos->cnext)
+    for (pos = (head)->c_next; pos != (head); pos = pos->c_next)
 
 /**
- * list_for_each_prev	-	iterate over a list backwards
- * @pos:	the &struct list_head to use as a loop cursor.
- * @head:	the head for your list.
+ * list_for_each_prev    -    iterate over a list backwards
+ * @pos:    the &struct list_head to use as a loop cursor.
+ * @head:    the head for your list.
  */
 #define list_for_each_prev(pos, head) \
-	for (pos = (head)->cprev; prefetch(pos->cprev), pos != (head); \
-			pos = pos->cprev)
+    for (pos = (head)->c_prev; prefetch(pos->c_prev), pos != (head); \
+            pos = pos->c_prev)
 
 /**
  * list_for_each_safe - iterate over a list safe against removal of list entry
- * @pos:	the &struct list_head to use as a loop cursor.
- * @n:		another &struct list_head to use as temporary storage
- * @head:	the head for your list.
+ * @pos:    the &struct list_head to use as a loop cursor.
+ * @n:        another &struct list_head to use as temporary storage
+ * @head:    the head for your list.
  */
 #define list_for_each_safe(pos, n, head) \
-	for (pos = (head)->cnext, n = pos->cnext; pos != (head); \
-		pos = n, n = pos->cnext)
+    for (pos = (head)->c_next, n = pos->c_next; pos != (head); \
+        pos = n, n = pos->c_next)
 
 /**
  * list_for_each_prev_safe - iterate over a list backwards safe against removal of list entry
- * @pos:	the &struct list_head to use as a loop cursor.
- * @n:		another &struct list_head to use as temporary storage
- * @head:	the head for your list.
+ * @pos:    the &struct list_head to use as a loop cursor.
+ * @n:        another &struct list_head to use as temporary storage
+ * @head:    the head for your list.
  */
 #define list_for_each_prev_safe(pos, n, head) \
-	for (pos = (head)->cprev, n = pos->cprev; \
-	     prefetch(pos->cprev), pos != (head); \
-	     pos = n, n = pos->cprev)
+    for (pos = (head)->c_prev, n = pos->c_prev; \
+         prefetch(pos->c_prev), pos != (head); \
+         pos = n, n = pos->c_prev)
 
 /**
- * list_for_each_entry	-	iterate over list of given type
- * @pos:	the type * to use as a loop cursor.
- * @head:	the head for your list.
- * @member:	the name of the list_struct within the struct.
+ * list_for_each_entry    -    iterate over list of given type
+ * @pos:    the type * to use as a loop cursor.
+ * @head:    the head for your list.
+ * @member:    the name of the list_struct within the struct.
  */
-#define list_for_each_entry(pos, head, member)				\
-	for (pos = list_entry((head)->cnext, typeof(*pos), member);	\
-	     prefetch(pos->member.cnext), &pos->member != (head); 	\
-	     pos = list_entry(pos->member.cnext, typeof(*pos), member))
+#define list_for_each_entry(pos, head, member)                \
+    for (pos = list_entry((head)->c_next, typeof(*pos), member);    \
+         prefetch(pos->member.c_next), &pos->member != (head);     \
+         pos = list_entry(pos->member.c_next, typeof(*pos), member))
 
 /**
  * list_for_each_entry_reverse - iterate backwards over list of given type.
- * @pos:	the type * to use as a loop cursor.
- * @head:	the head for your list.
- * @member:	the name of the list_struct within the struct.
+ * @pos:    the type * to use as a loop cursor.
+ * @head:    the head for your list.
+ * @member:    the name of the list_struct within the struct.
  */
-#define list_for_each_entry_reverse(pos, head, member)			\
-	for (pos = list_entry((head)->cprev, typeof(*pos), member);	\
-	     prefetch(pos->member.cprev), &pos->member != (head); 	\
-	     pos = list_entry(pos->member.cprev, typeof(*pos), member))
+#define list_for_each_entry_reverse(pos, head, member)            \
+    for (pos = list_entry((head)->c_prev, typeof(*pos), member);    \
+         prefetch(pos->member.c_prev), &pos->member != (head);     \
+         pos = list_entry(pos->member.c_prev, typeof(*pos), member))
 
 /**
  * list_prepare_entry - prepare a pos entry for use in list_for_each_entry_continue()
- * @pos:	the type * to use as a start point
- * @head:	the head of the list
- * @member:	the name of the list_struct within the struct.
+ * @pos:    the type * to use as a start point
+ * @head:    the head of the list
+ * @member:    the name of the list_struct within the struct.
  *
  * Prepares a pos entry for use as a start point in list_for_each_entry_continue().
  */
 #define list_prepare_entry(pos, head, member) \
-	((pos) ? : list_entry(head, typeof(*pos), member))
+    ((pos) ? : list_entry(head, typeof(*pos), member))
 
 /**
  * list_for_each_entry_continue - continue iteration over list of given type
- * @pos:	the type * to use as a loop cursor.
- * @head:	the head for your list.
- * @member:	the name of the list_struct within the struct.
+ * @pos:    the type * to use as a loop cursor.
+ * @head:    the head for your list.
+ * @member:    the name of the list_struct within the struct.
  *
  * Continue to iterate over list of given type, continuing after
  * the current position.
  */
-#define list_for_each_entry_continue(pos, head, member) 		\
-	for (pos = list_entry(pos->member.cnext, typeof(*pos), member);	\
-	     prefetch(pos->member.cnext), &pos->member != (head);	\
-	     pos = list_entry(pos->member.cnext, typeof(*pos), member))
+#define list_for_each_entry_continue(pos, head, member)         \
+    for (pos = list_entry(pos->member.c_next, typeof(*pos), member);    \
+         prefetch(pos->member.c_next), &pos->member != (head);    \
+         pos = list_entry(pos->member.c_next, typeof(*pos), member))
 
 /**
  * list_for_each_entry_continue_reverse - iterate backwards from the given point
- * @pos:	the type * to use as a loop cursor.
- * @head:	the head for your list.
- * @member:	the name of the list_struct within the struct.
+ * @pos:    the type * to use as a loop cursor.
+ * @head:    the head for your list.
+ * @member:    the name of the list_struct within the struct.
  *
  * Start to iterate over list of given type backwards, continuing after
  * the current position.
  */
-#define list_for_each_entry_continue_reverse(pos, head, member)		\
-	for (pos = list_entry(pos->member.cprev, typeof(*pos), member);	\
-	     prefetch(pos->member.cprev), &pos->member != (head);	\
-	     pos = list_entry(pos->member.cprev, typeof(*pos), member))
+#define list_for_each_entry_continue_reverse(pos, head, member)        \
+    for (pos = list_entry(pos->member.c_prev, typeof(*pos), member);    \
+         prefetch(pos->member.c_prev), &pos->member != (head);    \
+         pos = list_entry(pos->member.c_prev, typeof(*pos), member))
 
 /**
  * list_for_each_entry_from - iterate over list of given type from the current point
- * @pos:	the type * to use as a loop cursor.
- * @head:	the head for your list.
- * @member:	the name of the list_struct within the struct.
+ * @pos:    the type * to use as a loop cursor.
+ * @head:    the head for your list.
+ * @member:    the name of the list_struct within the struct.
  *
  * Iterate over list of given type, continuing from current position.
  */
-#define list_for_each_entry_from(pos, head, member) 			\
-	for (; prefetch(pos->member.cnext), &pos->member != (head);	\
-	     pos = list_entry(pos->member.cnext, typeof(*pos), member))
+#define list_for_each_entry_from(pos, head, member)             \
+    for (; prefetch(pos->member.c_next), &pos->member != (head);    \
+         pos = list_entry(pos->member.c_next, typeof(*pos), member))
 
 /**
  * list_for_each_entry_safe - iterate over list of given type safe against removal of list entry
- * @pos:	the type * to use as a loop cursor.
- * @n:		another type * to use as temporary storage
- * @head:	the head for your list.
- * @member:	the name of the list_struct within the struct.
+ * @pos:    the type * to use as a loop cursor.
+ * @n:        another type * to use as temporary storage
+ * @head:    the head for your list.
+ * @member:    the name of the list_struct within the struct.
  */
-#define list_for_each_entry_safe(pos, n, head, member)			\
-	for (pos = list_entry((head)->cnext, typeof(*pos), member),	\
-		n = list_entry(pos->member.cnext, typeof(*pos), member);	\
-	     &pos->member != (head); 					\
-	     pos = n, n = list_entry(n->member.cnext, typeof(*n), member))
+#define list_for_each_entry_safe(pos, n, head, member)            \
+    for (pos = list_entry((head)->c_next, typeof(*pos), member),    \
+        n = list_entry(pos->member.c_next, typeof(*pos), member);    \
+         &pos->member != (head);                     \
+         pos = n, n = list_entry(n->member.c_next, typeof(*n), member))
 
 /**
  * list_for_each_entry_safe_continue - continue list iteration safe against removal
- * @pos:	the type * to use as a loop cursor.
- * @n:		another type * to use as temporary storage
- * @head:	the head for your list.
- * @member:	the name of the list_struct within the struct.
+ * @pos:    the type * to use as a loop cursor.
+ * @n:        another type * to use as temporary storage
+ * @head:    the head for your list.
+ * @member:    the name of the list_struct within the struct.
  *
  * Iterate over list of given type, continuing after current point,
  * safe against removal of list entry.
  */
-#define list_for_each_entry_safe_continue(pos, n, head, member) 		\
-	for (pos = list_entry(pos->member.cnext, typeof(*pos), member), 		\
-		n = list_entry(pos->member.cnext, typeof(*pos), member);		\
-	     &pos->member != (head);						\
-	     pos = n, n = list_entry(n->member.cnext, typeof(*n), member))
+#define list_for_each_entry_safe_continue(pos, n, head, member)         \
+    for (pos = list_entry(pos->member.c_next, typeof(*pos), member),         \
+        n = list_entry(pos->member.c_next, typeof(*pos), member);        \
+         &pos->member != (head);                        \
+         pos = n, n = list_entry(n->member.c_next, typeof(*n), member))
 
 /**
  * list_for_each_entry_safe_from - iterate over list from current point safe against removal
- * @pos:	the type * to use as a loop cursor.
- * @n:		another type * to use as temporary storage
- * @head:	the head for your list.
- * @member:	the name of the list_struct within the struct.
+ * @pos:    the type * to use as a loop cursor.
+ * @n:        another type * to use as temporary storage
+ * @head:    the head for your list.
+ * @member:    the name of the list_struct within the struct.
  *
  * Iterate over list of given type from current point, safe against
  * removal of list entry.
  */
-#define list_for_each_entry_safe_from(pos, n, head, member) 			\
-	for (n = list_entry(pos->member.cnext, typeof(*pos), member);		\
-	     &pos->member != (head);						\
-	     pos = n, n = list_entry(n->member.cnext, typeof(*n), member))
+#define list_for_each_entry_safe_from(pos, n, head, member)             \
+    for (n = list_entry(pos->member.c_next, typeof(*pos), member);        \
+         &pos->member != (head);                        \
+         pos = n, n = list_entry(n->member.c_next, typeof(*n), member))
 
 /**
  * list_for_each_entry_safe_reverse - iterate backwards over list safe against removal
- * @pos:	the type * to use as a loop cursor.
- * @n:		another type * to use as temporary storage
- * @head:	the head for your list.
- * @member:	the name of the list_struct within the struct.
+ * @pos:    the type * to use as a loop cursor.
+ * @n:        another type * to use as temporary storage
+ * @head:    the head for your list.
+ * @member:    the name of the list_struct within the struct.
  *
  * Iterate backwards over list of given type, safe against removal
  * of list entry.
  */
-#define list_for_each_entry_safe_reverse(pos, n, head, member)		\
-	for (pos = list_entry((head)->cprev, typeof(*pos), member),	\
-		n = list_entry(pos->member.cprev, typeof(*pos), member);	\
-	     &pos->member != (head); 					\
-	     pos = n, n = list_entry(n->member.cprev, typeof(*n), member))
+#define list_for_each_entry_safe_reverse(pos, n, head, member)        \
+    for (pos = list_entry((head)->c_prev, typeof(*pos), member),    \
+        n = list_entry(pos->member.c_prev, typeof(*pos), member);    \
+         &pos->member != (head);                     \
+         pos = n, n = list_entry(n->member.c_prev, typeof(*n), member))
 
 /*
  * Double linked lists with a single pointer list head.
@@ -610,11 +610,11 @@
  */
 
 struct hlist_head {
-	struct hlist_node *first;
+    struct hlist_node *first;
 };
 
 struct hlist_node {
-	struct hlist_node *cnext, **pcprev;
+    struct hlist_node *c_next, **pc_prev;
 };
 
 #define HLIST_HEAD_INIT { .first = NULL }
@@ -622,147 +622,147 @@
 #define INIT_HLIST_HEAD(ptr) ((ptr)->first = NULL)
 static inline void INIT_HLIST_NODE(struct hlist_node *h)
 {
-	h->cnext = NULL;
-	h->pcprev = NULL;
+    h->c_next = NULL;
+    h->pc_prev = NULL;
 }
 
 static inline int hlist_unhashed(const struct hlist_node *h)
 {
-	return !h->pcprev;
+    return !h->pc_prev;
 }
 
 static inline int hlist_empty(const struct hlist_head *h)
 {
-	return !h->first;
+    return !h->first;
 }
 
 static inline void __hlist_del(struct hlist_node *n)
 {
-	struct hlist_node *cnext = n->cnext;
-	struct hlist_node **pcprev = n->pcprev;
-	*pcprev = cnext;
-	if (cnext)
-		cnext->pcprev = pcprev;
+    struct hlist_node *c_next = n->c_next;
+    struct hlist_node **pc_prev = n->pc_prev;
+    *pc_prev = c_next;
+    if (c_next)
+        c_next->pc_prev = pc_prev;
 }
 
 static inline void hlist_del(struct hlist_node *n)
 {
-	__hlist_del(n);
-	n->cnext = (struct hlist_node *)LIST_POISON1;
-	n->pcprev = (struct hlist_node **)LIST_POISON2;
+    __hlist_del(n);
+    n->c_next = (struct hlist_node *)LIST_POISON1;
+    n->pc_prev = (struct hlist_node **)LIST_POISON2;
 }
 
 static inline void hlist_del_init(struct hlist_node *n)
 {
-	if (!hlist_unhashed(n)) {
-		__hlist_del(n);
-		INIT_HLIST_NODE(n);
-	}
+    if (!hlist_unhashed(n)) {
+        __hlist_del(n);
+        INIT_HLIST_NODE(n);
+    }
 }
 
 static inline void hlist_add_head(struct hlist_node *n, struct hlist_head *h)
 {
-	struct hlist_node *first = h->first;
-	n->cnext = first;
-	if (first)
-		first->pcprev = &n->cnext;
-	h->first = n;
-	n->pcprev = &h->first;
+    struct hlist_node *first = h->first;
+    n->c_next = first;
+    if (first)
+        first->pc_prev = &n->c_next;
+    h->first = n;
+    n->pc_prev = &h->first;
 }
 
-/* cnext must be != NULL */
+/* c_next must be != NULL */
 static inline void hlist_add_before(struct hlist_node *n,
-					struct hlist_node *cnext)
+                    struct hlist_node *c_next)
 {
-	n->pcprev = cnext->pcprev;
-	n->cnext = cnext;
-	cnext->pcprev = &n->cnext;
-	*(n->pcprev) = n;
+    n->pc_prev = c_next->pc_prev;
+    n->c_next = c_next;
+    c_next->pc_prev = &n->c_next;
+    *(n->pc_prev) = n;
 }
 
 static inline void hlist_add_after(struct hlist_node *n,
-					struct hlist_node *cnext)
+                    struct hlist_node *c_next)
 {
-	cnext->cnext = n->cnext;
-	n->cnext = cnext;
-	cnext->pcprev = &n->cnext;
+    c_next->c_next = n->c_next;
+    n->c_next = c_next;
+    c_next->pc_prev = &n->c_next;
 
-	if(cnext->cnext)
-		cnext->cnext->pcprev  = &cnext->cnext;
+    if(c_next->c_next)
+        c_next->c_next->pc_prev  = &c_next->c_next;
 }
 
 /*
- * Move a list from one list head to another. Fixup the pcprev
+ * Move a list from one list head to another. Fixup the pc_prev
  * reference of the first entry if it exists.
  */
 static inline void hlist_move_list(struct hlist_head *old,
-				   struct hlist_head *cnew)
+                   struct hlist_head *c_new)
 {
-	cnew->first = old->first;
-	if (cnew->first)
-		cnew->first->pcprev = &cnew->first;
-	old->first = NULL;
+    c_new->first = old->first;
+    if (c_new->first)
+        c_new->first->pc_prev = &c_new->first;
+    old->first = NULL;
 }
 
 #define hlist_entry(ptr, type, member) container_of(ptr,type,member)
 
 #define hlist_for_each(pos, head) \
-	for (pos = (head)->first; pos && ({ prefetch(pos->cnext); 1; }); \
-	     pos = pos->cnext)
+    for (pos = (head)->first; pos && ({ prefetch(pos->c_next); 1; }); \
+         pos = pos->c_next)
 
 #define hlist_for_each_safe(pos, n, head) \
-	for (pos = (head)->first; pos && ({ n = pos->cnext; 1; }); \
-	     pos = n)
+    for (pos = (head)->first; pos && ({ n = pos->c_next; 1; }); \
+         pos = n)
 
 /**
- * hlist_for_each_entry	- iterate over list of given type
- * @tpos:	the type * to use as a loop cursor.
- * @pos:	the &struct hlist_node to use as a loop cursor.
- * @head:	the head for your list.
- * @member:	the name of the hlist_node within the struct.
+ * hlist_for_each_entry    - iterate over list of given type
+ * @tpos:    the type * to use as a loop cursor.
+ * @pos:    the &struct hlist_node to use as a loop cursor.
+ * @head:    the head for your list.
+ * @member:    the name of the hlist_node within the struct.
  */
-#define hlist_for_each_entry(tpos, pos, head, member)			 \
-	for (pos = (head)->first;					 \
-	     pos && ({ prefetch(pos->cnext); 1;}) &&			 \
-		({ tpos = hlist_entry(pos, typeof(*tpos), member); 1;}); \
-	     pos = pos->cnext)
+#define hlist_for_each_entry(tpos, pos, head, member)             \
+    for (pos = (head)->first;                     \
+         pos && ({ prefetch(pos->c_next); 1;}) &&             \
+        ({ tpos = hlist_entry(pos, typeof(*tpos), member); 1;}); \
+         pos = pos->c_next)
 
 /**
  * hlist_for_each_entry_continue - iterate over a hlist continuing after current point
- * @tpos:	the type * to use as a loop cursor.
- * @pos:	the &struct hlist_node to use as a loop cursor.
- * @member:	the name of the hlist_node within the struct.
+ * @tpos:    the type * to use as a loop cursor.
+ * @pos:    the &struct hlist_node to use as a loop cursor.
+ * @member:    the name of the hlist_node within the struct.
  */
-#define hlist_for_each_entry_continue(tpos, pos, member)		 \
-	for (pos = (pos)->cnext;						 \
-	     pos && ({ prefetch(pos->cnext); 1;}) &&			 \
-		({ tpos = hlist_entry(pos, typeof(*tpos), member); 1;}); \
-	     pos = pos->cnext)
+#define hlist_for_each_entry_continue(tpos, pos, member)         \
+    for (pos = (pos)->c_next;                         \
+         pos && ({ prefetch(pos->c_next); 1;}) &&             \
+        ({ tpos = hlist_entry(pos, typeof(*tpos), member); 1;}); \
+         pos = pos->c_next)
 
 /**
  * hlist_for_each_entry_from - iterate over a hlist continuing from current point
- * @tpos:	the type * to use as a loop cursor.
- * @pos:	the &struct hlist_node to use as a loop cursor.
- * @member:	the name of the hlist_node within the struct.
+ * @tpos:    the type * to use as a loop cursor.
+ * @pos:    the &struct hlist_node to use as a loop cursor.
+ * @member:    the name of the hlist_node within the struct.
  */
-#define hlist_for_each_entry_from(tpos, pos, member)			 \
-	for (; pos && ({ prefetch(pos->cnext); 1;}) &&			 \
-		({ tpos = hlist_entry(pos, typeof(*tpos), member); 1;}); \
-	     pos = pos->cnext)
+#define hlist_for_each_entry_from(tpos, pos, member)             \
+    for (; pos && ({ prefetch(pos->c_next); 1;}) &&             \
+        ({ tpos = hlist_entry(pos, typeof(*tpos), member); 1;}); \
+         pos = pos->c_next)
 
 /**
  * hlist_for_each_entry_safe - iterate over list of given type safe against removal of list entry
- * @tpos:	the type * to use as a loop cursor.
- * @pos:	the &struct hlist_node to use as a loop cursor.
- * @n:		another &struct hlist_node to use as temporary storage
- * @head:	the head for your list.
- * @member:	the name of the hlist_node within the struct.
+ * @tpos:    the type * to use as a loop cursor.
+ * @pos:    the &struct hlist_node to use as a loop cursor.
+ * @n:        another &struct hlist_node to use as temporary storage
+ * @head:    the head for your list.
+ * @member:    the name of the hlist_node within the struct.
  */
-#define hlist_for_each_entry_safe(tpos, pos, n, head, member) 		 \
-	for (pos = (head)->first;					 \
-	     pos && ({ n = pos->cnext; 1; }) && 				 \
-		({ tpos = hlist_entry(pos, typeof(*tpos), member); 1;}); \
-	     pos = n)
+#define hlist_for_each_entry_safe(tpos, pos, n, head, member)          \
+    for (pos = (head)->first;                     \
+         pos && ({ n = pos->c_next; 1; }) &&                  \
+        ({ tpos = hlist_entry(pos, typeof(*tpos), member); 1;}); \
+         pos = n)
 
 #ifdef __cplusplus
 }
diff --git a/include/record_device.h b/include/record_device.h
index 0321b91..234dd4f 100644
--- a/include/record_device.h
+++ b/include/record_device.h
@@ -39,7 +39,7 @@
  */
 int record_device_add_pid(Record_DeviceHandle_t handle, int pid);
 
-/**\brief Remoe a pid from the DVR record handle
+/**\brief Remove a pid from the DVR record handle
  * \param[in] handle, DVR device handle
  * \param[in] pid, pid value
  * \return DVR_SUCCESS On success
diff --git a/include/segment.h b/include/segment.h
index 00725ce..bcc2709 100644
--- a/include/segment.h
+++ b/include/segment.h
@@ -27,6 +27,7 @@
   char                  location[DVR_MAX_LOCATION_SIZE];        /**< Segment file location*/
   uint64_t              segment_id;                             /**< Segment index*/
   Segment_OpenMode_t    mode;                                   /**< Segment open mode*/
+  DVR_Bool_t            force_sysclock;                         /**< If ture, force to use system clock as PVR index time source. If false, libdvr can determine index time source based on actual situation*/
 } Segment_OpenParams_t;
 
 /**\brief Open a segment for a target giving some open parameters
@@ -97,26 +98,24 @@
  */
 loff_t segment_tell_position(Segment_Handle_t handle);
 
-/**\brief Tell the giving position time for the giving segment, used for playback
+/**\brief Tell position time of the given segment's postion. Function is used for playback.
  * \param[in] handle, Segment handle
- * \return The segment giving position time on success
- * \return error code on failure
+ * \param[in] position, Segment's file position
+ * \return position time in ms on success, or -1 on failure
  */
-uint64_t segment_tell_position_time(Segment_Handle_t handle, loff_t position);
+loff_t segment_tell_position_time(Segment_Handle_t handle, loff_t position);
 
-/**\brief Tell the current time for the giving segment, used for playback
+/**\brief Tell current playback time of the given segment. Function is used for playback.
  * \param[in] handle, Segment handle
- * \return The segment current time on success
- * \return error code on failure
+ * \return segment's current playback time in ms on success, or -1 on failure
  */
-uint64_t segment_tell_current_time(Segment_Handle_t handle);
+loff_t segment_tell_current_time(Segment_Handle_t handle);
 
-/**\brief Tell the total time for the giving segment
+/**\brief Tell total time of the given segment.
  * \param[in] handle, Segment handle
- * \return The segment total time on success
- * \return error code on failure
+ * \return The segment's total time in ms on success, or -1 on failure
  */
-uint64_t segment_tell_total_time(Segment_Handle_t handle);
+loff_t segment_tell_total_time(Segment_Handle_t handle);
 
 /**\brief Store the segment information to a file
  * \param[in] handle, The segment handle
@@ -126,6 +125,14 @@
  */
 int segment_store_info(Segment_Handle_t handle, Segment_StoreInfo_t *p_info);
 
+/**\brief Store the segment all information to a file
+ * \param[in] handle, The segment handle
+ * \param[in] p_info, The segment information pointer
+ * \return DVR_SUCCESS On success
+ * \return Error code On failure
+ */
+int segment_store_allInfo(Segment_Handle_t handle, Segment_StoreInfo_t *p_info);
+
 /**\brief Load the segment information from a file
  * \param[in] handle, The segment handle
  * \param[out] p_info, The segment information pointer
@@ -134,6 +141,15 @@
  */
 int segment_load_info(Segment_Handle_t handle, Segment_StoreInfo_t *p_info);
 
+/**\brief Load the segment information from a file
+ * \param[in] handle, The segment handle
+ * \param[out] p_info, The segment information pointer
+ * \return DVR_SUCCESS On success
+ * \return Error code On failure
+ */
+int segment_load_allInfo(Segment_Handle_t handle, struct list_head *list);
+
+
 /**\brief Delete the segment information file
  * \param[in] location, The record file's location
  * \param[in] segment_id, The segment's index
@@ -149,6 +165,18 @@
  */
 int segment_ongoing(Segment_Handle_t handle);
 
+/**\brief get current ongoing segment size
+ * \param[in] handle, The segment handle
+ * \return segment size
+ */
+off_t segment_get_cur_segment_size(Segment_Handle_t handle);
+
+/**\brief get current ongoing segment id
+ * \param[in] handle, The segment handle
+ * \return segment id
+ */
+uint64_t segment_get_cur_segment_id(Segment_Handle_t handle);
+
 
 #ifdef __cplusplus
 }
diff --git a/src/am_crypt.c b/src/am_crypt.c
index caf615d..91d8dcf 100644
--- a/src/am_crypt.c
+++ b/src/am_crypt.c
@@ -3,6 +3,8 @@
 #include "des.h"
 #include "am_crypt.h"
 
+#define printf(a...) ((void)0)
+
 typedef struct {
     AVDES des_cryptor;
     uint8_t cache[188];
@@ -11,151 +13,152 @@
 
 static int av_des_crypt_ts_packet(AVDES* d, uint8_t* dst, const uint8_t *src, int decrypt)
 {
-	int afc;
-	uint32_t afc_len = 0;
-	uint32_t crypt_len = 188;
-	uint8_t *p_in = src;
-	uint8_t *p_out = dst;
+    int afc;
+    int afc_len = 0;
+    int crypt_len = 188;
+    const uint8_t *p_in = src;
+    uint8_t *p_out = dst;
 
-	afc = (p_in[3] >> 4) & 0x3;
-	if (afc == 0x0 || afc == 0x2) {
-		/* No payload */
-		return 0;
-	}
+    afc = (p_in[3] >> 4) & 0x3;
+    if (afc == 0x0 || afc == 0x2) {
+        /* No payload */
+        return 0;
+    }
 
-	p_in += 4;
-	p_out += 4;
-	crypt_len -= 4;
-	if (afc == 0x3) {
-		/* Adaption field followed by payload */
-		afc_len = p_in[0];
-		p_in++;
-		p_out++;
-		crypt_len--;
-		p_in += afc_len;
-		p_out += afc_len;
-		crypt_len -= afc_len;
-		if (crypt_len < 0) {
-			printf("%s illegal adaption filed len %d\n", __func__, afc_len);
-			return -1;
-		}
-	}
+    p_in += 4;
+    p_out += 4;
+    crypt_len -= 4;
+    if (afc == 0x3) {
+        /* Adaption field followed by payload */
+        afc_len = p_in[0];
+        p_in++;
+        p_out++;
+        crypt_len--;
+        p_in += afc_len;
+        p_out += afc_len;
+        crypt_len -= afc_len;
+        if (crypt_len < 0) {
+            printf("%s illegal adaption filed len %d\n", __func__, afc_len);
+            return -1;
+        }
+    }
 
-	crypt_len = (crypt_len & 0xfffffff8);
-	if (crypt_len < 8) {
-		printf("%s payload crypt eln too short!!!\n", __func__);
-		return -1;
-	}
-	av_des_crypt(d, p_out, p_in, crypt_len/8, NULL, decrypt);
+    crypt_len = (crypt_len & 0xfffffff8);
+    if (crypt_len < 8) {
+        printf("%s payload crypt eln too short!!!\n", __func__);
+        return -1;
+    }
+    av_des_crypt(d, p_out, p_in, crypt_len/8, NULL, decrypt);
 
-	return 0;
+    return 0;
 }
 
 
 void *am_crypt_des_open(const uint8_t *key, const uint8_t *iv, int key_bits)
 {
-	am_cryptor_t *cryptor = (am_cryptor_t *)malloc(sizeof(am_cryptor_t));
-	if (cryptor) {
-		memset(cryptor, 0, sizeof(am_cryptor_t));
-		if (av_des_init(&cryptor->des_cryptor, key, key_bits)) {
-			free(cryptor);
-			return NULL;
-		}
-	}
-	return cryptor;
+    am_cryptor_t *cryptor = (am_cryptor_t *)malloc(sizeof(am_cryptor_t));
+    if (cryptor) {
+        memset(cryptor, 0, sizeof(am_cryptor_t));
+        if (av_des_init(&cryptor->des_cryptor, key, key_bits)) {
+            free(cryptor);
+            return NULL;
+        }
+    }
+    return cryptor;
 }
 
 int am_crypt_des_close(void *cryptor)
 {
-	if (cryptor)
-		free(cryptor);
-	return 0;
+    if (cryptor)
+        free(cryptor);
+    return 0;
 }
 
 int am_crypt_des_crypt(void* cryptor, uint8_t* dst,
-		       const uint8_t *src, uint32_t *len, int decrypt)
+               const uint8_t *src, int *len, int decrypt)
 {
-	uint32_t out_len = 0;
-	uint32_t left = *len;
-	uint32_t *p_out_len = len;
-	uint8_t *p_in = src;
-	uint8_t *p_out = dst;
-	uint8_t *p_cache = &((am_cryptor_t *)cryptor)->cache[0];
-	uint8_t *p_cache_len = &((am_cryptor_t *)cryptor)->cache_len;
+    int out_len = 0;
+    int left = *len;
+    int *p_out_len = len;
+    const uint8_t *p_in = src;
+    uint8_t *p_out = dst;
+    uint8_t *p_cache = &((am_cryptor_t *)cryptor)->cache[0];
+    int *p_cache_len = &((am_cryptor_t *)cryptor)->cache_len;
 
-	/* Check parameters*/
-	if (!p_in || !p_out) {
-		printf("%s bad params, in:%p:%d, out:%p:%d\n",
-			__func__, p_in, left,
-			p_out, left);
-		*p_out_len = 0;
-		return -1;
-	}
+    /* Check parameters*/
+    if (!p_in || !p_out) {
+        printf("%s bad params, in:%p:%d, out:%p:%d\n",
+            __func__, p_in, left,
+            p_out, left);
+        *p_out_len = 0;
+        return -1;
+    }
 
-	/* If less than one ts packet, just cache the data */
-	if (left + *p_cache_len < 188) {
-		printf("%s in_len:%d, cache_len:%d, just cache the data\n",
-			__func__, left, *p_cache_len);
-		memcpy(p_cache + *p_cache_len, p_in, left);
-		*p_cache_len += left;
-		*p_out_len = 0;
-		return 0;
-	}
+    /* If less than one ts packet, just cache the data */
+    if (left + *p_cache_len < 188) {
+        printf("%s in_len:%d, cache_len:%d, just cache the data\n",
+            __func__, left, *p_cache_len);
+        memcpy(p_cache + *p_cache_len, p_in, left);
+        *p_cache_len += left;
+        *p_out_len = 0;
+        return 0;
+    }
 
-	if (*p_cache_len > 0) {
-		/* p_out length must be at least more 188Bytes than p_in length */
+    if (*p_cache_len > 0) {
+        /* p_out length must be at least more 188Bytes than p_in length */
 #if 0
-		if (*p_out_len - left < 188) {
-			printf("%s p_out length %d is not enougth big\n",
-				__func__, *p_out_len);
-			return -1;
-		}
+        if (*p_out_len - left < 188) {
+            printf("%s p_out length %d is not enough big\n",
+                __func__, *p_out_len);
+            return -1;
+        }
 #endif
-		/* Process cache data */
-		memcpy(p_cache + *p_cache_len, p_in, 188 - ((am_cryptor_t *)cryptor)->cache_len);
-		av_des_crypt_ts_packet(
-			(AVDES *)&(((am_cryptor_t *)cryptor)->des_cryptor),
-			p_out, p_cache, decrypt);
-		left -=  (188 - *p_cache_len);
-		p_in += (188 - *p_cache_len);
-		p_out += 188;
-		out_len = 188;
-		printf("%s process cache data\n", __func__);
-	}
+        /* Process cache data */
+        memcpy(p_cache + *p_cache_len, p_in, 188 - ((am_cryptor_t *)cryptor)->cache_len);
+        memcpy(p_out, p_cache, 188);
+        av_des_crypt_ts_packet(
+            (AVDES *)&(((am_cryptor_t *)cryptor)->des_cryptor),
+            p_out, p_cache, decrypt);
+        left -=  (188 - *p_cache_len);
+        p_in += (188 - *p_cache_len);
+        p_out += 188;
+        out_len = 188;
+        printf("%s process cache data\n", __func__);
+    }
 
-	/* Process input buffer */
-	memcpy(p_out, p_in, left);
-	while (left) {
-		if (*p_in == 0x47) {
-			if (left < 188) {
-				printf("%s cache %#x bytes\n", __func__,
-					 left);
-				break;
-			}
+    /* Process input buffer */
+    memcpy(p_out, p_in, left);
+    while (left > 0) {
+        if (*p_in == 0x47) {
+            if (left < 188) {
+                printf("%s cache %#x bytes\n", __func__,
+                     left);
+                break;
+            }
 
-			av_des_crypt_ts_packet(
-				(AVDES *)&(((am_cryptor_t *)cryptor)->des_cryptor),
-				p_out, p_in, decrypt);
-			p_in += 188;
-			p_out += 188;
-			left -= 188;
-			out_len += 188;
-		} else {
-			p_in ++;
-			p_out++;
-			left --;
-			out_len++;
-			printf("%s not ts header, skip one byte\n", __func__);
-		}
-	}
+            av_des_crypt_ts_packet(
+                (AVDES *)&(((am_cryptor_t *)cryptor)->des_cryptor),
+                p_out, p_in, decrypt);
+            p_in += 188;
+            p_out += 188;
+            left -= 188;
+            out_len += 188;
+        } else {
+            p_in ++;
+            p_out++;
+            left --;
+            out_len++;
+            printf("%s not ts header, skip one byte\n", __func__);
+        }
+    }
 
-	/* Cache remain data */
-	if (left) {
-		memcpy(p_cache, p_in, left);
-	}
+    /* Cache remain data */
+    if (left) {
+        memcpy(p_cache, p_in, left);
+    }
 
-	*p_cache_len = left;
-	*p_out_len = out_len;
+    *p_cache_len = left;
+    *p_out_len = out_len;
 
-	return 0;
+    return 0;
 }
diff --git a/src/des.c b/src/des.c
index 25e1f1b..b0aac78 100644
--- a/src/des.c
+++ b/src/des.c
@@ -1,353 +1,352 @@
-/*

- * DES encryption/decryption

- * Copyright (c) 2007 Reimar Doeffinger

- *

- * This file is part of FFmpeg.

- *

- * FFmpeg is free software; you can redistribute it and/or

- * modify it under the terms of the GNU Lesser General Public

- * License as published by the Free Software Foundation; either

- * version 2.1 of the License, or (at your option) any later version.

- *

- * FFmpeg is distributed in the hope that it will be useful,

- * but WITHOUT ANY WARRANTY; without even the implied warranty of

- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU

- * Lesser General Public License for more details.

- *

- * You should have received a copy of the GNU Lesser General Public

- * License along with FFmpeg; if not, write to the Free Software

- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

- */

-

-#include <stdint.h>

-

-/*#include "avutil.h"

-#include "common.h"

-#include "intreadwrite.h"

-#include "mem.h"*/

-#include "des.h"

-

-#ifndef AV_RB64

-#define AV_RB64(x)                                      \

-     (((uint64_t)((const uint8_t*)(x))[0] << 56) |      \

-     ((uint64_t)((const uint8_t*)(x))[1] << 48) |       \

-     ((uint64_t)((const uint8_t*)(x))[2] << 40) |       \

-     ((uint64_t)((const uint8_t*)(x))[3] << 32) |       \

-     ((uint64_t)((const uint8_t*)(x))[4] << 24) |       \

-     ((uint64_t)((const uint8_t*)(x))[5] << 16) |       \

-     ((uint64_t)((const uint8_t*)(x))[6] <<  8) |       \

-      (uint64_t)((const uint8_t*)(x))[7])

-#endif

-

-#ifndef AV_WB64

-#define AV_WB64(p, val) do {                     \

-         uint64_t d = val;                       \

-         ((uint8_t*)(p))[7] = (d);               \

-         ((uint8_t*)(p))[6] = (d)>>8;            \

-         ((uint8_t*)(p))[5] = (d)>>16;           \

-         ((uint8_t*)(p))[4] = (d)>>24;           \

-         ((uint8_t*)(p))[3] = (d)>>32;           \

-         ((uint8_t*)(p))[2] = (d)>>40;           \

-         ((uint8_t*)(p))[1] = (d)>>48;           \

-         ((uint8_t*)(p))[0] = (d)>>56;           \

-     } while(0)

-#endif

-

-#define T(a, b, c, d, e, f, g, h) 64 - a, 64 - b, 64 - c, 64 - d, 64 - e, 64 - f, 64 - g, 64 - h

-static const uint8_t IP_shuffle[] = {

-    T(58, 50, 42, 34, 26, 18, 10, 2),

-    T(60, 52, 44, 36, 28, 20, 12, 4),

-    T(62, 54, 46, 38, 30, 22, 14, 6),

-    T(64, 56, 48, 40, 32, 24, 16, 8),

-    T(57, 49, 41, 33, 25, 17,  9, 1),

-    T(59, 51, 43, 35, 27, 19, 11, 3),

-    T(61, 53, 45, 37, 29, 21, 13, 5),

-    T(63, 55, 47, 39, 31, 23, 15, 7)

-};

-#undef T

-

-#if CONFIG_SMALL || defined(GENTABLES)

-#define T(a, b, c, d) 32 - a, 32 - b, 32 - c, 32 - d

-static const uint8_t P_shuffle[] = {

-    T(16,  7, 20, 21),

-    T(29, 12, 28, 17),

-    T( 1, 15, 23, 26),

-    T( 5, 18, 31, 10),

-    T( 2,  8, 24, 14),

-    T(32, 27,  3,  9),

-    T(19, 13, 30,  6),

-    T(22, 11,  4, 25)

-};

-#undef T

-#endif

-

-#define T(a, b, c, d, e, f, g) 64 - a, 64 - b, 64 - c, 64 - d, 64 - e, 64 - f, 64 - g

-static const uint8_t PC1_shuffle[] = {

-    T(57, 49, 41, 33, 25, 17,  9),

-    T( 1, 58, 50, 42, 34, 26, 18),

-    T(10,  2, 59, 51, 43, 35, 27),

-    T(19, 11,  3, 60, 52, 44, 36),

-    T(63, 55, 47, 39, 31, 23, 15),

-    T( 7, 62, 54, 46, 38, 30, 22),

-    T(14,  6, 61, 53, 45, 37, 29),

-    T(21, 13,  5, 28, 20, 12,  4)

-};

-#undef T

-

-#define T(a, b, c, d, e, f) 56 - a, 56 - b, 56 - c, 56 - d, 56 - e, 56 - f

-static const uint8_t PC2_shuffle[] = {

-    T(14, 17, 11, 24,  1,  5),

-    T( 3, 28, 15,  6, 21, 10),

-    T(23, 19, 12,  4, 26,  8),

-    T(16,  7, 27, 20, 13,  2),

-    T(41, 52, 31, 37, 47, 55),

-    T(30, 40, 51, 45, 33, 48),

-    T(44, 49, 39, 56, 34, 53),

-    T(46, 42, 50, 36, 29, 32)

-};

-#undef T

-

-#if CONFIG_SMALL

-static const uint8_t S_boxes[8][32] = {

-    { 0x0e, 0xf4, 0x7d, 0x41, 0xe2, 0x2f, 0xdb, 0x18, 0xa3, 0x6a, 0xc6, 0xbc, 0x95, 0x59, 0x30, 0x87,

-      0xf4, 0xc1, 0x8e, 0x28, 0x4d, 0x96, 0x12, 0x7b, 0x5f, 0xbc, 0x39, 0xe7, 0xa3, 0x0a, 0x65, 0xd0, },

-    { 0x3f, 0xd1, 0x48, 0x7e, 0xf6, 0x2b, 0x83, 0xe4, 0xc9, 0x07, 0x12, 0xad, 0x6c, 0x90, 0xb5, 0x5a,

-      0xd0, 0x8e, 0xa7, 0x1b, 0x3a, 0xf4, 0x4d, 0x21, 0xb5, 0x68, 0x7c, 0xc6, 0x09, 0x53, 0xe2, 0x9f, },

-    { 0xda, 0x70, 0x09, 0x9e, 0x36, 0x43, 0x6f, 0xa5, 0x21, 0x8d, 0x5c, 0xe7, 0xcb, 0xb4, 0xf2, 0x18,

-      0x1d, 0xa6, 0xd4, 0x09, 0x68, 0x9f, 0x83, 0x70, 0x4b, 0xf1, 0xe2, 0x3c, 0xb5, 0x5a, 0x2e, 0xc7, },

-    { 0xd7, 0x8d, 0xbe, 0x53, 0x60, 0xf6, 0x09, 0x3a, 0x41, 0x72, 0x28, 0xc5, 0x1b, 0xac, 0xe4, 0x9f,

-      0x3a, 0xf6, 0x09, 0x60, 0xac, 0x1b, 0xd7, 0x8d, 0x9f, 0x41, 0x53, 0xbe, 0xc5, 0x72, 0x28, 0xe4, },

-    { 0xe2, 0xbc, 0x24, 0xc1, 0x47, 0x7a, 0xdb, 0x16, 0x58, 0x05, 0xf3, 0xaf, 0x3d, 0x90, 0x8e, 0x69,

-      0xb4, 0x82, 0xc1, 0x7b, 0x1a, 0xed, 0x27, 0xd8, 0x6f, 0xf9, 0x0c, 0x95, 0xa6, 0x43, 0x50, 0x3e, },

-    { 0xac, 0xf1, 0x4a, 0x2f, 0x79, 0xc2, 0x96, 0x58, 0x60, 0x1d, 0xd3, 0xe4, 0x0e, 0xb7, 0x35, 0x8b,

-      0x49, 0x3e, 0x2f, 0xc5, 0x92, 0x58, 0xfc, 0xa3, 0xb7, 0xe0, 0x14, 0x7a, 0x61, 0x0d, 0x8b, 0xd6, },

-    { 0xd4, 0x0b, 0xb2, 0x7e, 0x4f, 0x90, 0x18, 0xad, 0xe3, 0x3c, 0x59, 0xc7, 0x25, 0xfa, 0x86, 0x61,

-      0x61, 0xb4, 0xdb, 0x8d, 0x1c, 0x43, 0xa7, 0x7e, 0x9a, 0x5f, 0x06, 0xf8, 0xe0, 0x25, 0x39, 0xc2, },

-    { 0x1d, 0xf2, 0xd8, 0x84, 0xa6, 0x3f, 0x7b, 0x41, 0xca, 0x59, 0x63, 0xbe, 0x05, 0xe0, 0x9c, 0x27,

-      0x27, 0x1b, 0xe4, 0x71, 0x49, 0xac, 0x8e, 0xd2, 0xf0, 0xc6, 0x9a, 0x0d, 0x3f, 0x53, 0x65, 0xb8,

-    }

-};

-#else

-/**

- * This table contains the results of applying both the S-box and P-shuffle.

- * It can be regenerated by compiling tests/des.c with "-DCONFIG_SMALL -DGENTABLES".

- */

-static const uint32_t S_boxes_P_shuffle[8][64] = {

-    { 0x00808200, 0x00000000, 0x00008000, 0x00808202, 0x00808002, 0x00008202, 0x00000002, 0x00008000,

-      0x00000200, 0x00808200, 0x00808202, 0x00000200, 0x00800202, 0x00808002, 0x00800000, 0x00000002,

-      0x00000202, 0x00800200, 0x00800200, 0x00008200, 0x00008200, 0x00808000, 0x00808000, 0x00800202,

-      0x00008002, 0x00800002, 0x00800002, 0x00008002, 0x00000000, 0x00000202, 0x00008202, 0x00800000,

-      0x00008000, 0x00808202, 0x00000002, 0x00808000, 0x00808200, 0x00800000, 0x00800000, 0x00000200,

-      0x00808002, 0x00008000, 0x00008200, 0x00800002, 0x00000200, 0x00000002, 0x00800202, 0x00008202,

-      0x00808202, 0x00008002, 0x00808000, 0x00800202, 0x00800002, 0x00000202, 0x00008202, 0x00808200,

-      0x00000202, 0x00800200, 0x00800200, 0x00000000, 0x00008002, 0x00008200, 0x00000000, 0x00808002, },

-    { 0x40084010, 0x40004000, 0x00004000, 0x00084010, 0x00080000, 0x00000010, 0x40080010, 0x40004010,

-      0x40000010, 0x40084010, 0x40084000, 0x40000000, 0x40004000, 0x00080000, 0x00000010, 0x40080010,

-      0x00084000, 0x00080010, 0x40004010, 0x00000000, 0x40000000, 0x00004000, 0x00084010, 0x40080000,

-      0x00080010, 0x40000010, 0x00000000, 0x00084000, 0x00004010, 0x40084000, 0x40080000, 0x00004010,

-      0x00000000, 0x00084010, 0x40080010, 0x00080000, 0x40004010, 0x40080000, 0x40084000, 0x00004000,

-      0x40080000, 0x40004000, 0x00000010, 0x40084010, 0x00084010, 0x00000010, 0x00004000, 0x40000000,

-      0x00004010, 0x40084000, 0x00080000, 0x40000010, 0x00080010, 0x40004010, 0x40000010, 0x00080010,

-      0x00084000, 0x00000000, 0x40004000, 0x00004010, 0x40000000, 0x40080010, 0x40084010, 0x00084000, },

-    { 0x00000104, 0x04010100, 0x00000000, 0x04010004, 0x04000100, 0x00000000, 0x00010104, 0x04000100,

-      0x00010004, 0x04000004, 0x04000004, 0x00010000, 0x04010104, 0x00010004, 0x04010000, 0x00000104,

-      0x04000000, 0x00000004, 0x04010100, 0x00000100, 0x00010100, 0x04010000, 0x04010004, 0x00010104,

-      0x04000104, 0x00010100, 0x00010000, 0x04000104, 0x00000004, 0x04010104, 0x00000100, 0x04000000,

-      0x04010100, 0x04000000, 0x00010004, 0x00000104, 0x00010000, 0x04010100, 0x04000100, 0x00000000,

-      0x00000100, 0x00010004, 0x04010104, 0x04000100, 0x04000004, 0x00000100, 0x00000000, 0x04010004,

-      0x04000104, 0x00010000, 0x04000000, 0x04010104, 0x00000004, 0x00010104, 0x00010100, 0x04000004,

-      0x04010000, 0x04000104, 0x00000104, 0x04010000, 0x00010104, 0x00000004, 0x04010004, 0x00010100, },

-    { 0x80401000, 0x80001040, 0x80001040, 0x00000040, 0x00401040, 0x80400040, 0x80400000, 0x80001000,

-      0x00000000, 0x00401000, 0x00401000, 0x80401040, 0x80000040, 0x00000000, 0x00400040, 0x80400000,

-      0x80000000, 0x00001000, 0x00400000, 0x80401000, 0x00000040, 0x00400000, 0x80001000, 0x00001040,

-      0x80400040, 0x80000000, 0x00001040, 0x00400040, 0x00001000, 0x00401040, 0x80401040, 0x80000040,

-      0x00400040, 0x80400000, 0x00401000, 0x80401040, 0x80000040, 0x00000000, 0x00000000, 0x00401000,

-      0x00001040, 0x00400040, 0x80400040, 0x80000000, 0x80401000, 0x80001040, 0x80001040, 0x00000040,

-      0x80401040, 0x80000040, 0x80000000, 0x00001000, 0x80400000, 0x80001000, 0x00401040, 0x80400040,

-      0x80001000, 0x00001040, 0x00400000, 0x80401000, 0x00000040, 0x00400000, 0x00001000, 0x00401040, },

-    { 0x00000080, 0x01040080, 0x01040000, 0x21000080, 0x00040000, 0x00000080, 0x20000000, 0x01040000,

-      0x20040080, 0x00040000, 0x01000080, 0x20040080, 0x21000080, 0x21040000, 0x00040080, 0x20000000,

-      0x01000000, 0x20040000, 0x20040000, 0x00000000, 0x20000080, 0x21040080, 0x21040080, 0x01000080,

-      0x21040000, 0x20000080, 0x00000000, 0x21000000, 0x01040080, 0x01000000, 0x21000000, 0x00040080,

-      0x00040000, 0x21000080, 0x00000080, 0x01000000, 0x20000000, 0x01040000, 0x21000080, 0x20040080,

-      0x01000080, 0x20000000, 0x21040000, 0x01040080, 0x20040080, 0x00000080, 0x01000000, 0x21040000,

-      0x21040080, 0x00040080, 0x21000000, 0x21040080, 0x01040000, 0x00000000, 0x20040000, 0x21000000,

-      0x00040080, 0x01000080, 0x20000080, 0x00040000, 0x00000000, 0x20040000, 0x01040080, 0x20000080, },

-    { 0x10000008, 0x10200000, 0x00002000, 0x10202008, 0x10200000, 0x00000008, 0x10202008, 0x00200000,

-      0x10002000, 0x00202008, 0x00200000, 0x10000008, 0x00200008, 0x10002000, 0x10000000, 0x00002008,

-      0x00000000, 0x00200008, 0x10002008, 0x00002000, 0x00202000, 0x10002008, 0x00000008, 0x10200008,

-      0x10200008, 0x00000000, 0x00202008, 0x10202000, 0x00002008, 0x00202000, 0x10202000, 0x10000000,

-      0x10002000, 0x00000008, 0x10200008, 0x00202000, 0x10202008, 0x00200000, 0x00002008, 0x10000008,

-      0x00200000, 0x10002000, 0x10000000, 0x00002008, 0x10000008, 0x10202008, 0x00202000, 0x10200000,

-      0x00202008, 0x10202000, 0x00000000, 0x10200008, 0x00000008, 0x00002000, 0x10200000, 0x00202008,

-      0x00002000, 0x00200008, 0x10002008, 0x00000000, 0x10202000, 0x10000000, 0x00200008, 0x10002008, },

-    { 0x00100000, 0x02100001, 0x02000401, 0x00000000, 0x00000400, 0x02000401, 0x00100401, 0x02100400,

-      0x02100401, 0x00100000, 0x00000000, 0x02000001, 0x00000001, 0x02000000, 0x02100001, 0x00000401,

-      0x02000400, 0x00100401, 0x00100001, 0x02000400, 0x02000001, 0x02100000, 0x02100400, 0x00100001,

-      0x02100000, 0x00000400, 0x00000401, 0x02100401, 0x00100400, 0x00000001, 0x02000000, 0x00100400,

-      0x02000000, 0x00100400, 0x00100000, 0x02000401, 0x02000401, 0x02100001, 0x02100001, 0x00000001,

-      0x00100001, 0x02000000, 0x02000400, 0x00100000, 0x02100400, 0x00000401, 0x00100401, 0x02100400,

-      0x00000401, 0x02000001, 0x02100401, 0x02100000, 0x00100400, 0x00000000, 0x00000001, 0x02100401,

-      0x00000000, 0x00100401, 0x02100000, 0x00000400, 0x02000001, 0x02000400, 0x00000400, 0x00100001, },

-    { 0x08000820, 0x00000800, 0x00020000, 0x08020820, 0x08000000, 0x08000820, 0x00000020, 0x08000000,

-      0x00020020, 0x08020000, 0x08020820, 0x00020800, 0x08020800, 0x00020820, 0x00000800, 0x00000020,

-      0x08020000, 0x08000020, 0x08000800, 0x00000820, 0x00020800, 0x00020020, 0x08020020, 0x08020800,

-      0x00000820, 0x00000000, 0x00000000, 0x08020020, 0x08000020, 0x08000800, 0x00020820, 0x00020000,

-      0x00020820, 0x00020000, 0x08020800, 0x00000800, 0x00000020, 0x08020020, 0x00000800, 0x00020820,

-      0x08000800, 0x00000020, 0x08000020, 0x08020000, 0x08020020, 0x08000000, 0x00020000, 0x08000820,

-      0x00000000, 0x08020820, 0x00020020, 0x08000020, 0x08020000, 0x08000800, 0x08000820, 0x00000000,

-      0x08020820, 0x00020800, 0x00020800, 0x00000820, 0x00000820, 0x00020020, 0x08000000, 0x08020800, },

-};

-#endif

-

-static uint64_t shuffle(uint64_t in, const uint8_t *shuffle, int shuffle_len)

-{

-    int i;

-    uint64_t res = 0;

-    for (i = 0; i < shuffle_len; i++)

-        res += res + ((in >> *shuffle++) & 1);

-    return res;

-}

-

-static uint64_t shuffle_inv(uint64_t in, const uint8_t *shuffle, int shuffle_len)

-{

-    int i;

-    uint64_t res = 0;

-    shuffle += shuffle_len - 1;

-    for (i = 0; i < shuffle_len; i++) {

-        res |= (in & 1) << *shuffle--;

-        in >>= 1;

-    }

-    return res;

-}

-

-static uint32_t f_func(uint32_t r, uint64_t k)

-{

-    int i;

-    uint32_t out = 0;

-    // rotate to get first part of E-shuffle in the lowest 6 bits

-    r = (r << 1) | (r >> 31);

-    // apply S-boxes, those compress the data again from 8 * 6 to 8 * 4 bits

-    for (i = 7; i >= 0; i--) {

-        uint8_t tmp = (r ^ k) & 0x3f;

-#if CONFIG_SMALL

-        uint8_t v = S_boxes[i][tmp >> 1];

-        if (tmp & 1)

-            v >>= 4;

-        out = (out >> 4) | (v << 28);

-#else

-        out |= S_boxes_P_shuffle[i][tmp];

-#endif

-        // get next 6 bits of E-shuffle and round key k into the lowest bits

-        r   = (r >> 4) | (r << 28);

-        k >>= 6;

-    }

-#if CONFIG_SMALL

-    out = shuffle(out, P_shuffle, sizeof(P_shuffle));

-#endif

-    return out;

-}

-

-/**

- * @brief rotate the two halves of the expanded 56 bit key each 1 bit left

- *

- * Note: the specification calls this "shift", so I kept it although

- * it is confusing.

- */

-static uint64_t key_shift_left(uint64_t CDn)

-{

-    uint64_t carries = (CDn >> 27) & 0x10000001;

-    CDn <<= 1;

-    CDn  &= ~0x10000001;

-    CDn  |= carries;

-    return CDn;

-}

-

-static void gen_roundkeys(uint64_t K[16], uint64_t key)

-{

-    int i;

-    // discard parity bits from key and shuffle it into C and D parts

-    uint64_t CDn = shuffle(key, PC1_shuffle, sizeof(PC1_shuffle));

-    // generate round keys

-    for (i = 0; i < 16; i++) {

-        CDn = key_shift_left(CDn);

-        if (i > 1 && i != 8 && i != 15)

-            CDn = key_shift_left(CDn);

-        K[i] = shuffle(CDn, PC2_shuffle, sizeof(PC2_shuffle));

-    }

-}

-

-static uint64_t des_encdec(uint64_t in, uint64_t K[16], int decrypt)

-{

-    int i;

-    // used to apply round keys in reverse order for decryption

-    decrypt = decrypt ? 15 : 0;

-    // shuffle irrelevant to security but to ease hardware implementations

-    in = shuffle(in, IP_shuffle, sizeof(IP_shuffle));

-    for (i = 0; i < 16; i++) {

-        uint32_t f_res;

-        f_res = f_func(in, K[decrypt ^ i]);

-        in    = (in << 32) | (in >> 32);

-        in   ^= f_res;

-    }

-    in = (in << 32) | (in >> 32);

-    // reverse shuffle used to ease hardware implementations

-    in = shuffle_inv(in, IP_shuffle, sizeof(IP_shuffle));

-    return in;

-}

-

-int av_des_init(AVDES *d, const uint8_t *key, int key_bits) {

-    if (key_bits != 64 && key_bits != 192)

-        return -1;//AVERROR(EINVAL);

-    d->triple_des = key_bits > 64;

-    gen_roundkeys(d->round_keys[0], AV_RB64(key));

-    if (d->triple_des) {

-        gen_roundkeys(d->round_keys[1], AV_RB64(key +  8));

-        gen_roundkeys(d->round_keys[2], AV_RB64(key + 16));

-    }

-    return 0;

-}

-

-static void av_des_crypt_mac(AVDES *d, uint8_t *dst, const uint8_t *src,

-                             int count, uint8_t *iv, int decrypt, int mac)

-{

-    uint64_t iv_val = iv ? AV_RB64(iv) : 0;

-    while (count-- > 0) {

-        uint64_t dst_val;

-        uint64_t src_val = src ? AV_RB64(src) : 0;

-        if (decrypt) {

-            uint64_t tmp = src_val;

-            if (d->triple_des) {

-                src_val = des_encdec(src_val, d->round_keys[2], 1);

-                src_val = des_encdec(src_val, d->round_keys[1], 0);

-            }

-            dst_val = des_encdec(src_val, d->round_keys[0], 1) ^ iv_val;

-            iv_val  = iv ? tmp : 0;

-        } else {

-            dst_val = des_encdec(src_val ^ iv_val, d->round_keys[0], 0);

-            if (d->triple_des) {

-                dst_val = des_encdec(dst_val, d->round_keys[1], 1);

-                dst_val = des_encdec(dst_val, d->round_keys[2], 0);

-            }

-            iv_val = iv ? dst_val : 0;

-        }

-        AV_WB64(dst, dst_val);

-        src += 8;

-        if (!mac)

-            dst += 8;

-    }

-    if (iv)

-        AV_WB64(iv, iv_val);

-}

-

-void av_des_crypt(AVDES *d, uint8_t *dst, const uint8_t *src,

-                  int count, uint8_t *iv, int decrypt)

-{

-    av_des_crypt_mac(d, dst, src, count, iv, decrypt, 0);

-}

-

-void av_des_mac(AVDES *d, uint8_t *dst, const uint8_t *src, int count)

-{

-    av_des_crypt_mac(d, dst, src, count, (uint8_t[8]) { 0 }, 0, 1);

-}

-

+/*
+ * DES encryption/decryption
+ * Copyright (c) 2007 Reimar Doeffinger
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include <stdint.h>
+
+/*#include "avutil.h"
+#include "common.h"
+#include "mem.h"*/
+#include "des.h"
+
+#ifndef AV_RB64
+#define AV_RB64(x)                                      \
+     (((uint64_t)((const uint8_t*)(x))[0] << 56) |      \
+     ((uint64_t)((const uint8_t*)(x))[1] << 48) |       \
+     ((uint64_t)((const uint8_t*)(x))[2] << 40) |       \
+     ((uint64_t)((const uint8_t*)(x))[3] << 32) |       \
+     ((uint64_t)((const uint8_t*)(x))[4] << 24) |       \
+     ((uint64_t)((const uint8_t*)(x))[5] << 16) |       \
+     ((uint64_t)((const uint8_t*)(x))[6] <<  8) |       \
+      (uint64_t)((const uint8_t*)(x))[7])
+#endif
+
+#ifndef AV_WB64
+#define AV_WB64(p, val) do {                     \
+         uint64_t _d = val;                       \
+         ((uint8_t*)(p))[7] = (_d);               \
+         ((uint8_t*)(p))[6] = (_d)>>8;            \
+         ((uint8_t*)(p))[5] = (_d)>>16;           \
+         ((uint8_t*)(p))[4] = (_d)>>24;           \
+         ((uint8_t*)(p))[3] = (_d)>>32;           \
+         ((uint8_t*)(p))[2] = (_d)>>40;           \
+         ((uint8_t*)(p))[1] = (_d)>>48;           \
+         ((uint8_t*)(p))[0] = (_d)>>56;           \
+     } while(0)
+#endif
+
+#define T(a, b, c, d, e, f, g, h) 64 - a, 64 - b, 64 - c, 64 - d, 64 - e, 64 - f, 64 - g, 64 - h
+static const uint8_t IP_shuffle[] = {
+    T(58, 50, 42, 34, 26, 18, 10, 2),
+    T(60, 52, 44, 36, 28, 20, 12, 4),
+    T(62, 54, 46, 38, 30, 22, 14, 6),
+    T(64, 56, 48, 40, 32, 24, 16, 8),
+    T(57, 49, 41, 33, 25, 17,  9, 1),
+    T(59, 51, 43, 35, 27, 19, 11, 3),
+    T(61, 53, 45, 37, 29, 21, 13, 5),
+    T(63, 55, 47, 39, 31, 23, 15, 7)
+};
+#undef T
+
+#if CONFIG_SMALL || defined(GENTABLES)
+#define T(a, b, c, d) 32 - a, 32 - b, 32 - c, 32 - d
+static const uint8_t P_shuffle[] = {
+    T(16,  7, 20, 21),
+    T(29, 12, 28, 17),
+    T( 1, 15, 23, 26),
+    T( 5, 18, 31, 10),
+    T( 2,  8, 24, 14),
+    T(32, 27,  3,  9),
+    T(19, 13, 30,  6),
+    T(22, 11,  4, 25)
+};
+#undef T
+#endif
+
+#define T(a, b, c, d, e, f, g) 64 - a, 64 - b, 64 - c, 64 - d, 64 - e, 64 - f, 64 - g
+static const uint8_t PC1_shuffle[] = {
+    T(57, 49, 41, 33, 25, 17,  9),
+    T( 1, 58, 50, 42, 34, 26, 18),
+    T(10,  2, 59, 51, 43, 35, 27),
+    T(19, 11,  3, 60, 52, 44, 36),
+    T(63, 55, 47, 39, 31, 23, 15),
+    T( 7, 62, 54, 46, 38, 30, 22),
+    T(14,  6, 61, 53, 45, 37, 29),
+    T(21, 13,  5, 28, 20, 12,  4)
+};
+#undef T
+
+#define T(a, b, c, d, e, f) 56 - a, 56 - b, 56 - c, 56 - d, 56 - e, 56 - f
+static const uint8_t PC2_shuffle[] = {
+    T(14, 17, 11, 24,  1,  5),
+    T( 3, 28, 15,  6, 21, 10),
+    T(23, 19, 12,  4, 26,  8),
+    T(16,  7, 27, 20, 13,  2),
+    T(41, 52, 31, 37, 47, 55),
+    T(30, 40, 51, 45, 33, 48),
+    T(44, 49, 39, 56, 34, 53),
+    T(46, 42, 50, 36, 29, 32)
+};
+#undef T
+
+#if CONFIG_SMALL
+static const uint8_t S_boxes[8][32] = {
+    { 0x0e, 0xf4, 0x7d, 0x41, 0xe2, 0x2f, 0xdb, 0x18, 0xa3, 0x6a, 0xc6, 0xbc, 0x95, 0x59, 0x30, 0x87,
+      0xf4, 0xc1, 0x8e, 0x28, 0x4d, 0x96, 0x12, 0x7b, 0x5f, 0xbc, 0x39, 0xe7, 0xa3, 0x0a, 0x65, 0xd0, },
+    { 0x3f, 0xd1, 0x48, 0x7e, 0xf6, 0x2b, 0x83, 0xe4, 0xc9, 0x07, 0x12, 0xad, 0x6c, 0x90, 0xb5, 0x5a,
+      0xd0, 0x8e, 0xa7, 0x1b, 0x3a, 0xf4, 0x4d, 0x21, 0xb5, 0x68, 0x7c, 0xc6, 0x09, 0x53, 0xe2, 0x9f, },
+    { 0xda, 0x70, 0x09, 0x9e, 0x36, 0x43, 0x6f, 0xa5, 0x21, 0x8d, 0x5c, 0xe7, 0xcb, 0xb4, 0xf2, 0x18,
+      0x1d, 0xa6, 0xd4, 0x09, 0x68, 0x9f, 0x83, 0x70, 0x4b, 0xf1, 0xe2, 0x3c, 0xb5, 0x5a, 0x2e, 0xc7, },
+    { 0xd7, 0x8d, 0xbe, 0x53, 0x60, 0xf6, 0x09, 0x3a, 0x41, 0x72, 0x28, 0xc5, 0x1b, 0xac, 0xe4, 0x9f,
+      0x3a, 0xf6, 0x09, 0x60, 0xac, 0x1b, 0xd7, 0x8d, 0x9f, 0x41, 0x53, 0xbe, 0xc5, 0x72, 0x28, 0xe4, },
+    { 0xe2, 0xbc, 0x24, 0xc1, 0x47, 0x7a, 0xdb, 0x16, 0x58, 0x05, 0xf3, 0xaf, 0x3d, 0x90, 0x8e, 0x69,
+      0xb4, 0x82, 0xc1, 0x7b, 0x1a, 0xed, 0x27, 0xd8, 0x6f, 0xf9, 0x0c, 0x95, 0xa6, 0x43, 0x50, 0x3e, },
+    { 0xac, 0xf1, 0x4a, 0x2f, 0x79, 0xc2, 0x96, 0x58, 0x60, 0x1d, 0xd3, 0xe4, 0x0e, 0xb7, 0x35, 0x8b,
+      0x49, 0x3e, 0x2f, 0xc5, 0x92, 0x58, 0xfc, 0xa3, 0xb7, 0xe0, 0x14, 0x7a, 0x61, 0x0d, 0x8b, 0xd6, },
+    { 0xd4, 0x0b, 0xb2, 0x7e, 0x4f, 0x90, 0x18, 0xad, 0xe3, 0x3c, 0x59, 0xc7, 0x25, 0xfa, 0x86, 0x61,
+      0x61, 0xb4, 0xdb, 0x8d, 0x1c, 0x43, 0xa7, 0x7e, 0x9a, 0x5f, 0x06, 0xf8, 0xe0, 0x25, 0x39, 0xc2, },
+    { 0x1d, 0xf2, 0xd8, 0x84, 0xa6, 0x3f, 0x7b, 0x41, 0xca, 0x59, 0x63, 0xbe, 0x05, 0xe0, 0x9c, 0x27,
+      0x27, 0x1b, 0xe4, 0x71, 0x49, 0xac, 0x8e, 0xd2, 0xf0, 0xc6, 0x9a, 0x0d, 0x3f, 0x53, 0x65, 0xb8,
+    }
+};
+#else
+/**
+ * This table contains the results of applying both the S-box and P-shuffle.
+ * It can be regenerated by compiling tests/des.c with "-DCONFIG_SMALL -DGENTABLES".
+ */
+static const uint32_t S_boxes_P_shuffle[8][64] = {
+    { 0x00808200, 0x00000000, 0x00008000, 0x00808202, 0x00808002, 0x00008202, 0x00000002, 0x00008000,
+      0x00000200, 0x00808200, 0x00808202, 0x00000200, 0x00800202, 0x00808002, 0x00800000, 0x00000002,
+      0x00000202, 0x00800200, 0x00800200, 0x00008200, 0x00008200, 0x00808000, 0x00808000, 0x00800202,
+      0x00008002, 0x00800002, 0x00800002, 0x00008002, 0x00000000, 0x00000202, 0x00008202, 0x00800000,
+      0x00008000, 0x00808202, 0x00000002, 0x00808000, 0x00808200, 0x00800000, 0x00800000, 0x00000200,
+      0x00808002, 0x00008000, 0x00008200, 0x00800002, 0x00000200, 0x00000002, 0x00800202, 0x00008202,
+      0x00808202, 0x00008002, 0x00808000, 0x00800202, 0x00800002, 0x00000202, 0x00008202, 0x00808200,
+      0x00000202, 0x00800200, 0x00800200, 0x00000000, 0x00008002, 0x00008200, 0x00000000, 0x00808002, },
+    { 0x40084010, 0x40004000, 0x00004000, 0x00084010, 0x00080000, 0x00000010, 0x40080010, 0x40004010,
+      0x40000010, 0x40084010, 0x40084000, 0x40000000, 0x40004000, 0x00080000, 0x00000010, 0x40080010,
+      0x00084000, 0x00080010, 0x40004010, 0x00000000, 0x40000000, 0x00004000, 0x00084010, 0x40080000,
+      0x00080010, 0x40000010, 0x00000000, 0x00084000, 0x00004010, 0x40084000, 0x40080000, 0x00004010,
+      0x00000000, 0x00084010, 0x40080010, 0x00080000, 0x40004010, 0x40080000, 0x40084000, 0x00004000,
+      0x40080000, 0x40004000, 0x00000010, 0x40084010, 0x00084010, 0x00000010, 0x00004000, 0x40000000,
+      0x00004010, 0x40084000, 0x00080000, 0x40000010, 0x00080010, 0x40004010, 0x40000010, 0x00080010,
+      0x00084000, 0x00000000, 0x40004000, 0x00004010, 0x40000000, 0x40080010, 0x40084010, 0x00084000, },
+    { 0x00000104, 0x04010100, 0x00000000, 0x04010004, 0x04000100, 0x00000000, 0x00010104, 0x04000100,
+      0x00010004, 0x04000004, 0x04000004, 0x00010000, 0x04010104, 0x00010004, 0x04010000, 0x00000104,
+      0x04000000, 0x00000004, 0x04010100, 0x00000100, 0x00010100, 0x04010000, 0x04010004, 0x00010104,
+      0x04000104, 0x00010100, 0x00010000, 0x04000104, 0x00000004, 0x04010104, 0x00000100, 0x04000000,
+      0x04010100, 0x04000000, 0x00010004, 0x00000104, 0x00010000, 0x04010100, 0x04000100, 0x00000000,
+      0x00000100, 0x00010004, 0x04010104, 0x04000100, 0x04000004, 0x00000100, 0x00000000, 0x04010004,
+      0x04000104, 0x00010000, 0x04000000, 0x04010104, 0x00000004, 0x00010104, 0x00010100, 0x04000004,
+      0x04010000, 0x04000104, 0x00000104, 0x04010000, 0x00010104, 0x00000004, 0x04010004, 0x00010100, },
+    { 0x80401000, 0x80001040, 0x80001040, 0x00000040, 0x00401040, 0x80400040, 0x80400000, 0x80001000,
+      0x00000000, 0x00401000, 0x00401000, 0x80401040, 0x80000040, 0x00000000, 0x00400040, 0x80400000,
+      0x80000000, 0x00001000, 0x00400000, 0x80401000, 0x00000040, 0x00400000, 0x80001000, 0x00001040,
+      0x80400040, 0x80000000, 0x00001040, 0x00400040, 0x00001000, 0x00401040, 0x80401040, 0x80000040,
+      0x00400040, 0x80400000, 0x00401000, 0x80401040, 0x80000040, 0x00000000, 0x00000000, 0x00401000,
+      0x00001040, 0x00400040, 0x80400040, 0x80000000, 0x80401000, 0x80001040, 0x80001040, 0x00000040,
+      0x80401040, 0x80000040, 0x80000000, 0x00001000, 0x80400000, 0x80001000, 0x00401040, 0x80400040,
+      0x80001000, 0x00001040, 0x00400000, 0x80401000, 0x00000040, 0x00400000, 0x00001000, 0x00401040, },
+    { 0x00000080, 0x01040080, 0x01040000, 0x21000080, 0x00040000, 0x00000080, 0x20000000, 0x01040000,
+      0x20040080, 0x00040000, 0x01000080, 0x20040080, 0x21000080, 0x21040000, 0x00040080, 0x20000000,
+      0x01000000, 0x20040000, 0x20040000, 0x00000000, 0x20000080, 0x21040080, 0x21040080, 0x01000080,
+      0x21040000, 0x20000080, 0x00000000, 0x21000000, 0x01040080, 0x01000000, 0x21000000, 0x00040080,
+      0x00040000, 0x21000080, 0x00000080, 0x01000000, 0x20000000, 0x01040000, 0x21000080, 0x20040080,
+      0x01000080, 0x20000000, 0x21040000, 0x01040080, 0x20040080, 0x00000080, 0x01000000, 0x21040000,
+      0x21040080, 0x00040080, 0x21000000, 0x21040080, 0x01040000, 0x00000000, 0x20040000, 0x21000000,
+      0x00040080, 0x01000080, 0x20000080, 0x00040000, 0x00000000, 0x20040000, 0x01040080, 0x20000080, },
+    { 0x10000008, 0x10200000, 0x00002000, 0x10202008, 0x10200000, 0x00000008, 0x10202008, 0x00200000,
+      0x10002000, 0x00202008, 0x00200000, 0x10000008, 0x00200008, 0x10002000, 0x10000000, 0x00002008,
+      0x00000000, 0x00200008, 0x10002008, 0x00002000, 0x00202000, 0x10002008, 0x00000008, 0x10200008,
+      0x10200008, 0x00000000, 0x00202008, 0x10202000, 0x00002008, 0x00202000, 0x10202000, 0x10000000,
+      0x10002000, 0x00000008, 0x10200008, 0x00202000, 0x10202008, 0x00200000, 0x00002008, 0x10000008,
+      0x00200000, 0x10002000, 0x10000000, 0x00002008, 0x10000008, 0x10202008, 0x00202000, 0x10200000,
+      0x00202008, 0x10202000, 0x00000000, 0x10200008, 0x00000008, 0x00002000, 0x10200000, 0x00202008,
+      0x00002000, 0x00200008, 0x10002008, 0x00000000, 0x10202000, 0x10000000, 0x00200008, 0x10002008, },
+    { 0x00100000, 0x02100001, 0x02000401, 0x00000000, 0x00000400, 0x02000401, 0x00100401, 0x02100400,
+      0x02100401, 0x00100000, 0x00000000, 0x02000001, 0x00000001, 0x02000000, 0x02100001, 0x00000401,
+      0x02000400, 0x00100401, 0x00100001, 0x02000400, 0x02000001, 0x02100000, 0x02100400, 0x00100001,
+      0x02100000, 0x00000400, 0x00000401, 0x02100401, 0x00100400, 0x00000001, 0x02000000, 0x00100400,
+      0x02000000, 0x00100400, 0x00100000, 0x02000401, 0x02000401, 0x02100001, 0x02100001, 0x00000001,
+      0x00100001, 0x02000000, 0x02000400, 0x00100000, 0x02100400, 0x00000401, 0x00100401, 0x02100400,
+      0x00000401, 0x02000001, 0x02100401, 0x02100000, 0x00100400, 0x00000000, 0x00000001, 0x02100401,
+      0x00000000, 0x00100401, 0x02100000, 0x00000400, 0x02000001, 0x02000400, 0x00000400, 0x00100001, },
+    { 0x08000820, 0x00000800, 0x00020000, 0x08020820, 0x08000000, 0x08000820, 0x00000020, 0x08000000,
+      0x00020020, 0x08020000, 0x08020820, 0x00020800, 0x08020800, 0x00020820, 0x00000800, 0x00000020,
+      0x08020000, 0x08000020, 0x08000800, 0x00000820, 0x00020800, 0x00020020, 0x08020020, 0x08020800,
+      0x00000820, 0x00000000, 0x00000000, 0x08020020, 0x08000020, 0x08000800, 0x00020820, 0x00020000,
+      0x00020820, 0x00020000, 0x08020800, 0x00000800, 0x00000020, 0x08020020, 0x00000800, 0x00020820,
+      0x08000800, 0x00000020, 0x08000020, 0x08020000, 0x08020020, 0x08000000, 0x00020000, 0x08000820,
+      0x00000000, 0x08020820, 0x00020020, 0x08000020, 0x08020000, 0x08000800, 0x08000820, 0x00000000,
+      0x08020820, 0x00020800, 0x00020800, 0x00000820, 0x00000820, 0x00020020, 0x08000000, 0x08020800, },
+};
+#endif
+
+static uint64_t shuffle(uint64_t in, const uint8_t *shuffle, int shuffle_len)
+{
+    int i;
+    uint64_t res = 0;
+    for (i = 0; i < shuffle_len; i++)
+        res += res + ((in >> *shuffle++) & 1);
+    return res;
+}
+
+static uint64_t shuffle_inv(uint64_t in, const uint8_t *shuffle, int shuffle_len)
+{
+    int i;
+    uint64_t res = 0;
+    shuffle += shuffle_len - 1;
+    for (i = 0; i < shuffle_len; i++) {
+        res |= (in & 1) << *shuffle--;
+        in >>= 1;
+    }
+    return res;
+}
+
+static uint32_t f_func(uint32_t r, uint64_t k)
+{
+    int i;
+    uint32_t out = 0;
+    // rotate to get first part of E-shuffle in the lowest 6 bits
+    r = (r << 1) | (r >> 31);
+    // apply S-boxes, those compress the data again from 8 * 6 to 8 * 4 bits
+    for (i = 7; i >= 0; i--) {
+        uint8_t tmp = (r ^ k) & 0x3f;
+#if CONFIG_SMALL
+        uint8_t v = S_boxes[i][tmp >> 1];
+        if (tmp & 1)
+            v >>= 4;
+        out = (out >> 4) | (v << 28);
+#else
+        out |= S_boxes_P_shuffle[i][tmp];
+#endif
+        // get next 6 bits of E-shuffle and round key k into the lowest bits
+        r   = (r >> 4) | (r << 28);
+        k >>= 6;
+    }
+#if CONFIG_SMALL
+    out = shuffle(out, P_shuffle, sizeof(P_shuffle));
+#endif
+    return out;
+}
+
+/**
+ * @brief rotate the two halves of the expanded 56 bit key each 1 bit left
+ *
+ * Note: the specification calls this "shift", so I kept it although
+ * it is confusing.
+ */
+static uint64_t key_shift_left(uint64_t CDn)
+{
+    uint64_t carries = (CDn >> 27) & 0x10000001;
+    CDn <<= 1;
+    CDn  &= ~0x10000001;
+    CDn  |= carries;
+    return CDn;
+}
+
+static void gen_roundkeys(uint64_t K[16], uint64_t key)
+{
+    int i;
+    // discard parity bits from key and shuffle it into C and D parts
+    uint64_t CDn = shuffle(key, PC1_shuffle, sizeof(PC1_shuffle));
+    // generate round keys
+    for (i = 0; i < 16; i++) {
+        CDn = key_shift_left(CDn);
+        if (i > 1 && i != 8 && i != 15)
+            CDn = key_shift_left(CDn);
+        K[i] = shuffle(CDn, PC2_shuffle, sizeof(PC2_shuffle));
+    }
+}
+
+static uint64_t des_encdec(uint64_t in, uint64_t K[16], int decrypt)
+{
+    int i;
+    // used to apply round keys in reverse order for decryption
+    decrypt = decrypt ? 15 : 0;
+    // shuffle irrelevant to security but to ease hardware implementations
+    in = shuffle(in, IP_shuffle, sizeof(IP_shuffle));
+    for (i = 0; i < 16; i++) {
+        uint32_t f_res;
+        f_res = f_func(in, K[decrypt ^ i]);
+        in    = (in << 32) | (in >> 32);
+        in   ^= f_res;
+    }
+    in = (in << 32) | (in >> 32);
+    // reverse shuffle used to ease hardware implementations
+    in = shuffle_inv(in, IP_shuffle, sizeof(IP_shuffle));
+    return in;
+}
+
+int av_des_init(AVDES *d, const uint8_t *key, int key_bits) {
+    if (key_bits != 64 && key_bits != 192)
+        return -1;//AVERROR(EINVAL);
+    d->triple_des = key_bits > 64;
+    gen_roundkeys(d->round_keys[0], AV_RB64(key));
+    if (d->triple_des) {
+        gen_roundkeys(d->round_keys[1], AV_RB64(key +  8));
+        gen_roundkeys(d->round_keys[2], AV_RB64(key + 16));
+    }
+    return 0;
+}
+
+static void av_des_crypt_mac(AVDES *d, uint8_t *dst, const uint8_t *src,
+                             int count, uint8_t *iv, int decrypt, int mac)
+{
+    uint64_t iv_val = iv ? AV_RB64(iv) : 0;
+    while (count-- > 0) {
+        uint64_t dst_val;
+        uint64_t src_val = src ? AV_RB64(src) : 0;
+        if (decrypt) {
+            uint64_t tmp = src_val;
+            if (d->triple_des) {
+                src_val = des_encdec(src_val, d->round_keys[2], 1);
+                src_val = des_encdec(src_val, d->round_keys[1], 0);
+            }
+            dst_val = des_encdec(src_val, d->round_keys[0], 1) ^ iv_val;
+            iv_val  = iv ? tmp : 0;
+        } else {
+            dst_val = des_encdec(src_val ^ iv_val, d->round_keys[0], 0);
+            if (d->triple_des) {
+                dst_val = des_encdec(dst_val, d->round_keys[1], 1);
+                dst_val = des_encdec(dst_val, d->round_keys[2], 0);
+            }
+            iv_val = iv ? dst_val : 0;
+        }
+        AV_WB64(dst, dst_val);
+        src += 8;
+        if (!mac)
+            dst += 8;
+    }
+    if (iv)
+        AV_WB64(iv, iv_val);
+}
+
+void av_des_crypt(AVDES *d, uint8_t *dst, const uint8_t *src,
+                  int count, uint8_t *iv, int decrypt)
+{
+    av_des_crypt_mac(d, dst, src, count, iv, decrypt, 0);
+}
+
+void av_des_mac(AVDES *d, uint8_t *dst, const uint8_t *src, int count)
+{
+    av_des_crypt_mac(d, dst, src, count, (uint8_t[8]) { 0 }, 0, 1);
+}
+
diff --git a/src/dvb_dmx_wrapper.c b/src/dvb_dmx_wrapper.c
index 5bdc0a4..9b321db 100644
--- a/src/dvb_dmx_wrapper.c
+++ b/src/dvb_dmx_wrapper.c
@@ -59,14 +59,14 @@
 
 static inline DVB_RESULT dmx_get_dev(int dev_no, dvb_dmx_t **dev)
 {
-	if ((dev_no < 0) || (dev_no >= DMX_COUNT))
-	{
-		DVB_DEBUG(1, "invalid demux device number %d, must in(%d~%d)", dev_no, 0, DMX_COUNT-1);
-		return DVB_FAILURE;
-	}
+    if ((dev_no < 0) || (dev_no >= DMX_COUNT))
+    {
+        DVB_INFO("invalid demux device number %d, must in(%d~%d)", dev_no, 0, DMX_COUNT-1);
+        return DVB_FAILURE;
+    }
 
-	*dev = &dmx_devices[dev_no];
-	return DVB_SUCCESS;
+    *dev = &dmx_devices[dev_no];
+    return DVB_SUCCESS;
 }
 
 static void* dmx_data_thread(void *arg)
@@ -103,61 +103,65 @@
            if (dmx->filter[fid].used)
            {
                fds[cnt].events = POLLIN | POLLERR;
+               // It is not necessary to protect code block below with
+               // Record_DeviceContext_t.lock, so the following annotation
+               // is given to suppress related Coverity complaint.
+               // coverity[missing_lock]
                fds[cnt].fd = dmx->filter[fid].fd;
                fids[cnt] = fid;
                cnt++;
            }
         }
 
-    	pthread_mutex_unlock(&dmx->lock);
+        pthread_mutex_unlock(&dmx->lock);
 
-    	if (!cnt)
+        if (!cnt)
         {
             usleep(20*1000);
-    	    continue;
+            continue;
         }
 
-    	ret = poll(fds, cnt, DMX_POLL_TIMEOUT);
-    	if (ret <= 0)
-    	{
-    	    continue;
-    	}
+        ret = poll(fds, cnt, DMX_POLL_TIMEOUT);
+        if (ret <= 0)
+        {
+            continue;
+        }
 
-    	for (i = 0; i < cnt; i++)
-    	{
-    	    if (fds[i].revents & (POLLIN | POLLERR))
-    	    {
-        		pthread_mutex_lock(&dmx->lock);
-        		filter = &dmx->filter[fids[i]];
-        		if (!filter->enable || !filter->used || filter->need_free)
-        		{
-        		    DVB_DEBUG(1, "ch[%d] not used, not read", fids[i]);
-        		    len = 0;
-        		}
-        		else
-        		{
+        for (i = 0; i < cnt; i++)
+        {
+            if (fds[i].revents & (POLLIN | POLLERR))
+            {
+                pthread_mutex_lock(&dmx->lock);
+                filter = &dmx->filter[fids[i]];
+                if (!filter->enable || !filter->used || filter->need_free)
+                {
+                    DVB_INFO("ch[%d] not used, not read", fids[i]);
+                    len = 0;
+                }
+                else
+                {
                      len = read(filter->fd, sec_buf, SEC_BUF_SIZE);
                      if (len <= 0)
                      {
-                         DVB_DEBUG(1, "read demux filter[%d] failed (%s) %d", fids[i], strerror(errno), errno);
+                         DVB_INFO("read demux filter[%d] failed (%s) %d", fids[i], strerror(errno), errno);
                      }
-        		}
-        		pthread_mutex_unlock(&dmx->lock);
+                }
+                pthread_mutex_unlock(&dmx->lock);
 #ifdef DEBUG_DEMUX_DATA
-        		if (len)
-        		    DVB_DEBUG(1, "tid[%#x] ch[%d] %#x bytes", sec_buf[0], fids[i], len);
+                if (len)
+                    DVB_INFO("tid[%x] ch[%d] %x bytes", sec_buf[0], fids[i], len);
 #endif
-        		if (len > 0 && filter->cb)
-        		{
-        		    filter->cb(filter->dev_no, fids[i], sec_buf, len, filter->user_data);
-        		}
-    	    }
-    	}
+                if (len > 0 && filter->cb)
+                {
+                    filter->cb(filter->dev_no, fids[i], sec_buf, len, filter->user_data);
+                }
+            }
+        }
     }
 
     if (sec_buf)
     {
-	    free(sec_buf);
+        free(sec_buf);
     }
 
     return NULL;
@@ -167,14 +171,14 @@
 {
     if (fhandle >= DMX_FILTER_COUNT)
     {
-    	DVB_DEBUG(1, "wrong filter no");
-    	return NULL;
+        DVB_INFO("wrong filter no");
+        return NULL;
     }
 
     if (!dev->filter[fhandle].used)
     {
-    	DVB_DEBUG(1, "filter %d not allocated", fhandle);
-    	return NULL;
+        DVB_INFO("filter %d not allocated", fhandle);
+        return NULL;
     }
     return &dev->filter[fhandle];
 }
@@ -192,11 +196,11 @@
 
     if (dev->running)
     {
-	    DVB_DEBUG(1, "dmx already initialized");
-	    return DVB_FAILURE;
+        DVB_INFO("dmx already initialized");
+        return DVB_FAILURE;
     }
 
-	dev->dev_no = dev_no;
+    dev->dev_no = dev_no;
 
     pthread_mutex_init(&dev->lock, NULL);
     dev->running = 1;
@@ -221,7 +225,7 @@
 
     if (dmx_get_dev(dev_no, &dev))
     {
-        DVB_DEBUG(1, "demux allocate failed, wrong dmx device no %d", dev_no);
+        DVB_INFO("demux allocate failed, wrong dmx device no %d", dev_no);
         return DVB_FAILURE;
     }
 
@@ -229,15 +233,15 @@
     filter = &dev->filter[0];
     for (fid = 0; fid < DMX_FILTER_COUNT; fid++)
     {
-    	if (!filter[fid].used)
-    	{
-    	    break;
-    	}
+        if (!filter[fid].used)
+        {
+            break;
+        }
     }
 
     if (fid >= DMX_FILTER_COUNT)
     {
-        DVB_DEBUG(1, "filter id:%d, have no filter to alloc", fid);
+        DVB_INFO("filter id:%d, have no filter to alloc", fid);
         pthread_mutex_unlock(&dev->lock);
         return DVB_FAILURE;
     }
@@ -247,7 +251,7 @@
     fd = open(dev_name, O_RDWR);
     if (fd == -1)
     {
-        DVB_DEBUG(1, "cannot open \"%s\" (%s)", dev_name, strerror(errno));
+        DVB_INFO("cannot open \"%s\" (%s)", dev_name, strerror(errno));
         pthread_mutex_unlock(&dev->lock);
         return DVB_FAILURE;
     }
@@ -260,7 +264,7 @@
 
     pthread_mutex_unlock(&dev->lock);
 
-    //DVB_DEBUG(1, "fhandle = %d", fid);
+    //DVB_INFO("fhandle = %d", fid);
     return DVB_SUCCESS;
 }
 
@@ -278,7 +282,7 @@
 
     if (dmx_get_dev(dev_no, &dev))
     {
-        DVB_DEBUG(1, "Wrong dmx device no %d", dev_no);
+        DVB_INFO("Wrong dmx device no %d", dev_no);
         return DVB_FAILURE;
     }
 
@@ -290,20 +294,20 @@
     filter = dmx_get_filter(dev, fhandle);
     if (filter)
     {
-	   if (ioctl(filter->fd, DMX_STOP, 0) < 0)
-	   {
-		   DVB_DEBUG(1, "dmx stop filter failed error:%s", strerror(errno));
-		   ret = DVB_FAILURE;
-	   }
-	   else if (ioctl(filter->fd, DMX_SET_FILTER, params) < 0)
-	   {
-	   	  DVB_DEBUG(1, "set filter failed error:%s", strerror(errno));
-		  ret = DVB_FAILURE;
-	   }
+       if (ioctl(filter->fd, DMX_STOP, 0) < 0)
+       {
+           DVB_INFO("dmx stop filter failed error:%s", strerror(errno));
+           ret = DVB_FAILURE;
+       }
+       else if (ioctl(filter->fd, DMX_SET_FILTER, params) < 0)
+       {
+             DVB_INFO("set filter failed error:%s", strerror(errno));
+          ret = DVB_FAILURE;
+       }
     }
 
     pthread_mutex_unlock(&dev->lock);
-    //DVB_DEBUG(1, "pid = %#x", params->pid);
+    //DVB_INFO("pid = %x", params->pid);
     return ret;
 }
 
@@ -321,7 +325,7 @@
 
     if (dmx_get_dev(dev_no, &dev))
     {
-        DVB_DEBUG(1, "wrong dmx device no %d", dev_no);
+        DVB_ERROR("wrong dmx device no %d", dev_no);
         return DVB_FAILURE;
     }
 
@@ -333,24 +337,27 @@
     filter = dmx_get_filter(dev, fhandle);
     if (filter)
     {
-	   if (ioctl(filter->fd, DMX_STOP, 0) < 0)
-	   {
-               DVB_DEBUG(1, "dmx stop filter failed error:%s", strerror(errno));
-               ret = DVB_FAILURE;
-	   }
-	   else
-	   {
-	      fcntl(filter->fd, F_SETFL, O_NONBLOCK);
-	      if (ioctl(filter->fd, DMX_SET_PES_FILTER, params) < 0)
-	      {
-                  DVB_DEBUG(1, "set filter failed error:%s", strerror(errno));
-                  ret = DVB_FAILURE;
-              }
-	   }
+        ret = DVB_FAILURE;
+        if (ioctl(filter->fd, DMX_STOP, 0) < 0)
+        {
+            DVB_ERROR("stopping demux filter fails with errno:%d(%s)",errno,strerror(errno));
+        }
+        else if (fcntl(filter->fd, F_SETFL, O_NONBLOCK) < 0)
+        {
+            DVB_ERROR("setting filter non-block flag fails with errno:%d(%s)",errno,strerror(errno));
+        }
+        else if (ioctl(filter->fd, DMX_SET_PES_FILTER, params) < 0)
+        {
+            DVB_ERROR("setting PES filter fails with errno:%d(%s)",errno,strerror(errno));
+        }
+        else
+        {
+            ret = DVB_SUCCESS;
+        }
     }
 
     pthread_mutex_unlock(&dev->lock);
-    //DVB_DEBUG(1, "pid = %#x", params->pid);
+    //DVB_INFO("pid = %x", params->pid);
     return ret;
 }
 
@@ -368,7 +375,7 @@
 
     if (dmx_get_dev(dev_no, &dev))
     {
-        DVB_DEBUG(1, "wrong dmx device no %d", dev_no);
+        DVB_INFO("wrong dmx device no %d", dev_no);
         return DVB_FAILURE;
     }
 
@@ -377,11 +384,11 @@
     filter = dmx_get_filter(dev, fhandle);
     if (filter)
     {
-	    if (ioctl(filter->fd, DMX_SET_BUFFER_SIZE, size) < 0)
-	    {
- 	   	  DVB_DEBUG(1, "set buf size failed error:%s", strerror(errno));
-		  ret = DVB_FAILURE;
-		}
+        if (ioctl(filter->fd, DMX_SET_BUFFER_SIZE, size) < 0)
+        {
+              DVB_INFO("set buf size failed error:%s", strerror(errno));
+          ret = DVB_FAILURE;
+        }
     }
 
     pthread_mutex_unlock(&dev->lock);
@@ -400,7 +407,7 @@
 
     if (dmx_get_dev(dev_no, &dev))
     {
-        DVB_DEBUG(1, "wrong dmx device no %d", dev_no);
+        DVB_INFO("wrong dmx device no %d", dev_no);
         return DVB_FAILURE;
     }
 
@@ -409,12 +416,12 @@
     filter = dmx_get_filter(dev, fhandle);
     if (filter)
     {
-	    filter->need_free = 1;
+        filter->need_free = 1;
     }
 
     pthread_mutex_unlock(&dev->lock);
 
-    //DVB_DEBUG(1, "fhandle = %d", fhandle);
+    //DVB_INFO("fhandle = %d", fhandle);
     return DVB_SUCCESS;
 }
 
@@ -431,7 +438,7 @@
 
     if (dmx_get_dev(dev_no, &dev))
     {
-        DVB_DEBUG(1, "wrong dmx device no %d", dev_no);
+        DVB_INFO("wrong dmx device no %d", dev_no);
         return DVB_FAILURE;
     }
 
@@ -442,7 +449,7 @@
     {
         if (ioctl(filter->fd, DMX_START, 0) < 0)
         {
-            DVB_DEBUG(1, "dmx start filter failed error:%s", strerror(errno));
+            DVB_INFO("dmx start filter failed error:%s", strerror(errno));
             ret = DVB_FAILURE;
         }
         else
@@ -452,7 +459,7 @@
     }
 
     pthread_mutex_unlock(&dev->lock);
-    //DVB_DEBUG(1, "ret = %d", ret);
+    //DVB_INFO("ret = %d", ret);
     return ret;
 }
 
@@ -469,7 +476,7 @@
 
     if (dmx_get_dev(dev_no, &dev))
     {
-        DVB_DEBUG(1, "wrong dmx device no %d", dev_no);
+        DVB_INFO("wrong dmx device no %d", dev_no);
         return DVB_FAILURE;
     }
 
@@ -480,7 +487,7 @@
     {
         if (ioctl(filter->fd, DMX_STOP, 0) < 0)
         {
-            DVB_DEBUG(1, "dmx stop filter failed error:%s", strerror(errno));
+            DVB_INFO("dmx stop filter failed error:%s", strerror(errno));
             ret = DVB_FAILURE;
         }
         else
@@ -490,7 +497,7 @@
     }
 
     pthread_mutex_unlock(&dev->lock);
-    //DVB_DEBUG(1, "ret = %d", ret);
+    //DVB_INFO("ret = %d", ret);
     return ret;
 }
 
@@ -509,7 +516,7 @@
 
     if (dmx_get_dev(dev_no, &dev))
     {
-        DVB_DEBUG(1, "wrong dmx device no %d", dev_no);
+        DVB_INFO("wrong dmx device no %d", dev_no);
         return DVB_FAILURE;
     }
 
@@ -527,7 +534,7 @@
 
     pthread_mutex_unlock(&dev->lock);
 
-    //DVB_DEBUG(1, "ret = %d", ret);
+    //DVB_INFO("ret = %d", ret);
     return ret;
 }
 
@@ -539,12 +546,13 @@
 {
     int i;
     int open_count = 0;
-	dvb_dmx_t *dev = NULL;
+    dvb_dmx_t *dev = NULL;
     dvb_dmx_filter_t *filter = NULL;
+    DVB_RESULT ret = DVB_SUCCESS;
 
     if (dmx_get_dev(dev_no, &dev))
     {
-        DVB_DEBUG(1, "wrong dmx device no %d", dev_no);
+        DVB_ERROR("wrong dmx device no %d", dev_no);
         return DVB_FAILURE;
     }
 
@@ -552,28 +560,33 @@
 
     for (i = 0; i < DMX_FILTER_COUNT; i++)
     {
-    	filter = &dev->filter[i];
-    	if (filter->used && filter->dev_no == dev_no)
-    	{
-    	    if (filter->enable)
-    	    {
-                ioctl(filter->fd, DMX_STOP, 0);
-    	    }
-    	    close(filter->fd);
-    	}
-	else if (filter->used)
-    	{
-    	    open_count++;
-    	}
+        filter = &dev->filter[i];
+        if (filter->used && filter->dev_no == dev_no)
+        {
+            if (filter->enable)
+            {
+                if (ioctl(filter->fd, DMX_STOP, 0)<0)
+                {
+                    DVB_ERROR("fails to stop filter. fd:%d", filter->fd);
+                    ret = DVB_FAILURE;
+                }
+            }
+            close(filter->fd);
+        }
+        else if (filter->used)
+        {
+            open_count++;
+        }
     }
 
     if (open_count == 0)
     {
-       dev->running = 0;
-       pthread_join(dev->thread, NULL);
-       pthread_mutex_destroy(&dev->lock);
+        dev->running = 0;
+        pthread_join(dev->thread, NULL);
     }
 
     pthread_mutex_unlock(&dev->lock);
-    return DVB_SUCCESS;
+    pthread_mutex_destroy(&dev->lock);
+
+    return ret;
 }
diff --git a/src/dvb_frontend_wrapper.c b/src/dvb_frontend_wrapper.c
index 16a6d25..453bba9 100644
--- a/src/dvb_frontend_wrapper.c
+++ b/src/dvb_frontend_wrapper.c
@@ -37,7 +37,7 @@
 
     if ((*frontend_fd = open(name, O_RDWR | O_NONBLOCK)) < 0)
     {
-        DVB_DEBUG(1, "Failed to open tune:%s, errno[%d]:%s", name, errno, strerror(errno));
+        DVB_INFO("Failed to open tune:%s, errno[%d]:%s", name, errno, strerror(errno));
         retval = DVB_FAILURE;
     }
 
@@ -48,14 +48,14 @@
  * \param FE device fd
  * \return DVB_SUCCESS On success, DVB_FAILURE on error.
  */
-DVB_RESULT AML_FE_Colse(int frontend_fd)
+DVB_RESULT AML_FE_Close(int frontend_fd)
 {
     DVB_RESULT retval = DVB_SUCCESS;
 
     if (close(frontend_fd) < 0)
     {
         retval = DVB_FAILURE;
-        DVB_DEBUG(1, "Failed to close frontend_fd:%d, errno[%d]:%s", frontend_fd, errno, strerror(errno));
+        DVB_INFO("Failed to close frontend_fd:%d, errno[%d]:%s", frontend_fd, errno, strerror(errno));
     }
 
     return retval;
@@ -68,25 +68,25 @@
 dmd_tuner_event_t AML_FE_GetTuneStatus(int frontend_fd)
 {
     struct dvb_frontend_event fe_event;
-    dmd_tuner_event_t tune_event = TUNER_STATE_UNKNOW;
+    dmd_tuner_event_t tune_event = TUNER_STATE_UNKNOWN;
 
     if (ioctl(frontend_fd, FE_READ_STATUS, &fe_event.status) >= 0)
     {
-        DVB_DEBUG(1, "current tuner status=0x%02x \n", fe_event.status);
+        DVB_INFO("current tuner status=0x%02x \n", fe_event.status);
         if ((fe_event.status & FE_HAS_LOCK) != 0)
         {
             tune_event = TUNER_STATE_LOCKED;
-            DVB_DEBUG(1, "[ LOCKED ]\n");
+            DVB_INFO("[ LOCKED ]\n");
         }
         else if ((fe_event.status & FE_TIMEDOUT) != 0)
         {
             tune_event = TUNER_STATE_TIMEOUT;
-            DVB_DEBUG(1, "[ UNLOCKED ]\n");
+            DVB_INFO("[ UNLOCKED ]\n");
         }
     }
     else
     {
-        DVB_DEBUG(1, "frontend_fd:%d FE_READ_STATUS errno[%d]:%s", frontend_fd, errno, strerror(errno));
+        DVB_INFO("frontend_fd:%d FE_READ_STATUS errno[%d]:%s", frontend_fd, errno, strerror(errno));
     }
 
     return tune_event;
@@ -191,9 +191,8 @@
         p[cmd_num].u.data = terr->desc.dvbt2.frequency * 1000;
     else
         p[cmd_num].u.data = terr->desc.dtmb.frequency * 1000;
-    DVB_DEBUG(1, "%s, type:%s, freq:%d", __func__,
-             (terr->dvb_type == DMD_DVBTYPE_DVBT) ? "DVB-T" : ((terr->dvb_type == DMD_DVBTYPE_DVBT2) ? "DVB-T2" : "DTMB"),
-             p[cmd_num].u.data);
+    char* dvb_type = ((terr->dvb_type == DMD_DVBTYPE_DVBT) ? "DVB-T" : ((terr->dvb_type == DMD_DVBTYPE_DVBT2) ? "DVB-T2" : "DTMB"));
+    DVB_INFO("%s, type:%s, freq:%d", __func__, dvb_type, p[cmd_num].u.data);
 
     p[cmd_num].cmd = DTV_FREQUENCY;
     cmd_num++;
@@ -292,9 +291,9 @@
     struct dtv_properties props;
     struct dtv_property p[DTV_IOCTL_MAX_MSGS];
 
-    DVB_DEBUG(1, "lock S, freq:%d, symbol rate:%d,  DVB-%s\n",
-             sate->frequency, sate->symbol_rate,
-             sate->modulation_system == DMD_MODSYS_DVBS2 ? "S2" : "S");
+    char* modulation_system = (sate->modulation_system == DMD_MODSYS_DVBS2 ? "S2" : "S");
+    DVB_INFO("lock S, freq:%d, symbol rate:%d,  DVB-%s\n",
+            sate->frequency, sate->symbol_rate, modulation_system);
 
     p[cmd_num].cmd = DTV_DELIVERY_SYSTEM;
     p[cmd_num].u.data = sate->modulation_system == DMD_MODSYS_DVBS2 ? SYS_DVBS2 : SYS_DVBS;
@@ -385,7 +384,7 @@
     if (ioctl(frontend_fd, FE_SET_VOLTAGE, volt) == -1)
     {
         ret = DVB_FAILURE;
-        DVB_DEBUG(1, "FE_SET_VOLTAGE failed, frontend_fd:%d, voltage:%d errno[%d]:%s", frontend_fd, voltage, errno, strerror(errno));
+        DVB_INFO("FE_SET_VOLTAGE failed, frontend_fd:%d, voltage:%d errno[%d]:%s", frontend_fd, voltage, errno, strerror(errno));
     }
     return ret;
 }
@@ -436,14 +435,14 @@
     for (int i = 0; i < size; i++)
     {
         cmd.msg[i] = data[i];
-        DVB_DEBUG(1, "AML_FE_SendDISEQCMessage cmd:0x%x", data[i]);
+        DVB_INFO("AML_FE_SendDISEQCMessage cmd:0x%x", data[i]);
     }
     cmd.msg_len = size;
 
     if (ioctl(frontend_fd, FE_DISEQC_SEND_MASTER_CMD, &cmd) == -1)
     {
         ret = DVB_FAILURE;
-        DVB_DEBUG(1, "FE_DISEQC_SEND_MASTER_CMD failed, frontend_fd:%d, errno[%d]:%s", frontend_fd, errno, strerror(errno));
+        DVB_INFO("FE_DISEQC_SEND_MASTER_CMD failed, frontend_fd:%d, errno[%d]:%s", frontend_fd, errno, strerror(errno));
     }
     return ret;
 }
@@ -452,7 +451,7 @@
 {
     if (ioctl(frontend_fd, FE_SET_PROPERTY, prop) == -1)
     {
-        DVB_DEBUG(1, "FE_SET_PROPERT failed, frontend_fd:%d, errno[%d]:%s", frontend_fd, errno, strerror(errno));
+        DVB_INFO("FE_SET_PROPERT failed, frontend_fd:%d, errno[%d]:%s", frontend_fd, errno, strerror(errno));
         return DVB_FAILURE;
     }
     return DVB_SUCCESS;
diff --git a/src/dvb_utils.c b/src/dvb_utils.c
index 9dbe99b..b0a490d 100644
--- a/src/dvb_utils.c
+++ b/src/dvb_utils.c
@@ -40,7 +40,7 @@
 
         for (i = 0; i < 3; i ++)
         {
-            DVB_DemuxSource_t src;
+            DVB_DemuxSource_t src = DVB_DEMUX_SOURCE_TS0;
 
             dvb_get_demux_source(i, &src);
             if (src != DVB_DEMUX_SOURCE_DMA0)
@@ -67,23 +67,22 @@
  */
 int dvb_set_demux_source(int dmx_idx, DVB_DemuxSource_t src)
 {
-    char node[32];
-    struct stat st;
-    int r;
+    char node[32] = {0};
+    char node2[20] = {0};
+    int r = 0;
 
     snprintf(node, sizeof(node), "/sys/class/stb/demux%d_source", dmx_idx);
+    snprintf(node2, sizeof(node2), "/dev/dvb0.demux%d", dmx_idx);
 
-    r = stat(node, &st);
-    if (r == -1)
+    int fd = open(node, O_RDONLY);
+    if (fd == -1)
     {
-        int fd, source, input = 0;
-        memset(node, 0, sizeof(node));
-        snprintf(node, sizeof(node), "/dev/dvb0.demux%d", dmx_idx);
-        fd = open(node, O_WRONLY);
-        if (fd != -1)
+        int source = 0;
+        int input = 0;
+        int fd2 = open(node2, O_WRONLY);
+        if (fd2 != -1)
         {
-            if (src >= DVB_DEMUX_SOURCE_TS0 &&
-                src <= DVB_DEMUX_SOURCE_TS7) {
+            if (src <= DVB_DEMUX_SOURCE_TS7) {
                 source = FRONTEND_TS0 + src - DVB_DEMUX_SOURCE_TS0;
                 input = INPUT_DEMOD;
             } else if (src >= DVB_DEMUX_SOURCE_DMA0 &&
@@ -110,36 +109,38 @@
                 assert(0);
             }
 
-            if (ioctl(fd, DMX_SET_INPUT, input) == -1)
+            if (ioctl(fd2, DMX_SET_INPUT, input) == -1)
             {
-                 DVR_DEBUG(1, "dvb_set_demux_source ioctl DMX_SET_INPUT:%d error:%d", input, errno);
+                 DVR_INFO("dvb_set_demux_source ioctl DMX_SET_INPUT:%d error:%d", input, errno);
                  r = -1;
             }
             else
             {
-                 DVR_DEBUG(1, "dvb_set_demux_source ioctl sucesss src:%d DMX_SET_INPUT:%d dmx_idx:%d", src, input, dmx_idx);
+                 DVR_INFO("dvb_set_demux_source ioctl succeeded src:%d DMX_SET_INPUT:%d dmx_idx:%d", src, input, dmx_idx);
                  r = 0;
             }
-            if (ioctl(fd, DMX_SET_HW_SOURCE, source) == -1)
+            if (ioctl(fd2, DMX_SET_HW_SOURCE, source) == -1)
             {
-                DVR_DEBUG(1, "dvb_set_demux_source ioctl DMX_SET_HW_SOURCE:%d error:%d", source, errno);
+                DVR_INFO("dvb_set_demux_source ioctl DMX_SET_HW_SOURCE:%d error:%d", source, errno);
                 r = -1;
             }
             else
             {
-                DVR_DEBUG(1, "dvb_set_demux_source ioctl sucesss src:%d DMX_SET_HW_SOURCE:%d dmx_idx:%d", src, source, dmx_idx);
+                DVR_INFO("dvb_set_demux_source ioctl succeeded src:%d DMX_SET_HW_SOURCE:%d dmx_idx:%d", src, source, dmx_idx);
                 r = 0;
             }
-            close(fd);
+            close(fd2);
         }
         else
         {
-            DVR_DEBUG(1, "dvb_set_demux_source open \"%s\" failed, error:%d", node, errno);
+            DVR_ERROR("dvb_set_demux_source open \"%s\" failed, error:%d", node, errno);
         }
     }
     else
     {
-        char *val;
+        char *val = NULL;
+
+        close(fd);
 
         if (ciplus_enable)
         {
@@ -150,7 +151,7 @@
 
             for (i = 0; i < 3; i ++)
             {
-                DVB_DemuxSource_t dmx_src;
+                DVB_DemuxSource_t dmx_src = DVB_DEMUX_SOURCE_TS0;
 
                 if (i == dmx_idx)
                     dmx_src = src;
@@ -205,21 +206,22 @@
 int dvb_get_demux_source(int dmx_idx, DVB_DemuxSource_t *src)
 {
     char node[32] = {0};
+    char node2[20] = {0};
     char buf[32] = {0};
-    struct stat st;
-    int r, source_no;
+    int r = 0;
+    int source_no = 0;
 
     snprintf(node, sizeof(node), "/sys/class/stb/demux%d_source", dmx_idx);
-    r = stat(node, &st);
-    if (r == -1)
+    snprintf(node2, sizeof(node2), "/dev/dvb0.demux%d", dmx_idx);
+
+    int fd = open(node, O_RDONLY);
+    if (fd == -1)
     {
-        int fd, source;
-        memset(node, 0, sizeof(node));
-        snprintf(node, sizeof(node), "/dev/dvb0.demux%d", dmx_idx);
-        fd = open(node, O_RDONLY);
-        if (fd != -1)
+        int source;
+        int fd2 = open(node2, O_RDONLY);
+        if (fd2 != -1)
         {
-            if (ioctl(fd, DMX_GET_HW_SOURCE, &source) != -1)
+            if (ioctl(fd2, DMX_GET_HW_SOURCE, &source) != -1)
             {
                 switch (source)
                 {
@@ -271,23 +273,48 @@
                 case DMA_7:
                     *src = DVB_DEMUX_SOURCE_DMA7;
                     break;
+                case FRONTEND_TS0_1:
+                    *src = DVB_DEMUX_SOURCE_TS0_1;
+                    break;
+                case FRONTEND_TS1_1:
+                    *src = DVB_DEMUX_SOURCE_TS1_1;
+                    break;
+                case FRONTEND_TS2_1:
+                    *src = DVB_DEMUX_SOURCE_TS2_1;
+                    break;
+                case FRONTEND_TS3_1:
+                    *src = DVB_DEMUX_SOURCE_TS3_1;
+                    break;
+                case FRONTEND_TS4_1:
+                    *src = DVB_DEMUX_SOURCE_TS4_1;
+                    break;
+                case FRONTEND_TS5_1:
+                    *src = DVB_DEMUX_SOURCE_TS5_1;
+                    break;
+                case FRONTEND_TS6_1:
+                    *src = DVB_DEMUX_SOURCE_TS6_1;
+                    break;
+                case FRONTEND_TS7_1:
+                    *src = DVB_DEMUX_SOURCE_TS7_1;
+                    break;
                 default:
                     assert(0);
                 }
             }
             else
             {
-                DVR_DEBUG(1, "ioctl DMX_GET_HW_SOURCE:%d error:%d", source, errno);
+                DVR_ERROR("ioctl DMX_GET_HW_SOURCE:%d error:%d", source, errno);
             }
-            close(fd);
+            close(fd2);
         }
         else
         {
-            DVR_DEBUG(1, "open \"%s\" failed, error:%d", node, errno);
+            DVR_ERROR("opening \"%s\" failed with errno:%d", node2, errno);
         }
     }
     else
     {
+        close(fd);
         r = dvr_file_read(node, buf, sizeof(buf));
         if (r != -1)
         {
@@ -306,7 +333,7 @@
                     *src = DVB_DEMUX_SOURCE_TS2;
                     break;
                 default:
-                    DVR_DEBUG(1, "do not support demux source:%s", buf);
+                    DVR_INFO("do not support demux source:%s", buf);
                     r = -1;
                     break;
                 }
@@ -319,7 +346,7 @@
             {
                 r = -1;
             }
-            DVR_DEBUG(1, "dvb_get_demux_source \"%s\" :%s", node, buf);
+            DVR_INFO("dvb_get_demux_source \"%s\" :%s", node, buf);
         }
     }
 
diff --git a/src/dvr_mutex.c b/src/dvr_mutex.c
new file mode 100644
index 0000000..1dd4fb0
--- /dev/null
+++ b/src/dvr_mutex.c
@@ -0,0 +1,128 @@
+#include <string.h>
+
+#include "dvr_types.h"
+#include "dvr_mutex.h"
+
+#define MUTEX_LOG_TAG "libdvr-mutex"
+#define mutex_error(...) DVR_LOG_PRINT(LOG_LV_ERROR, MUTEX_LOG_TAG, __VA_ARGS__)
+#define mutex_debug(...) DVR_LOG_PRINT(LOG_LV_DEBUG, MUTEX_LOG_TAG, __VA_ARGS__)
+
+
+void _dvr_mutex_init(void *mutex)
+{
+   if (!mutex) {
+      mutex_error("null mutex\n");
+      return;
+   }
+   dvr_mutex_t *mtx = (dvr_mutex_t*)mutex;
+   memset(mtx, 0, sizeof(dvr_mutex_t));
+   if (pthread_mutex_init(&mtx->lock, NULL) != 0) {
+      mutex_error("init mutex fail\n");
+      return;
+   }
+   mtx->thread = 0;
+   mtx->lock_cnt = 0;
+   return;
+}
+
+void _dvr_mutex_lock(void *mutex)
+{
+   if (!mutex) {
+      mutex_error("null mutex\n");
+      return;
+   }
+   dvr_mutex_t *mtx = (dvr_mutex_t*)mutex;
+   if (pthread_equal(mtx->thread, pthread_self()) != 0) {
+      mtx->lock_cnt++;
+   } else {
+      pthread_mutex_lock(&mtx->lock);
+      mtx->thread = pthread_self();
+      mtx->lock_cnt = 1;
+   }
+}
+
+void _dvr_mutex_unlock(void *mutex)
+{
+   if (!mutex) {
+      mutex_error("null mutex\n");
+      return;
+   }
+   dvr_mutex_t *mtx = (dvr_mutex_t*)mutex;
+   if (pthread_equal(mtx->thread, pthread_self()) != 0) {
+      mtx->lock_cnt--;
+      if (mtx->lock_cnt == 0) {
+         mtx->thread = 0;
+         pthread_mutex_unlock(&mtx->lock);
+      }
+   } else {
+      mutex_debug("not own mutex\n");
+   }
+}
+
+void _dvr_mutex_destroy(void *mutex)
+{
+   if (!mutex) {
+      mutex_error("null mutex\n");
+      return;
+   }
+   dvr_mutex_t *mtx = (dvr_mutex_t*)mutex;
+   pthread_mutex_destroy(&mtx->lock);
+}
+
+int _dvr_mutex_save(void *mutex)
+{
+   if (!mutex) {
+       mutex_error("null mutex\n");
+       return 0;
+   }
+   dvr_mutex_t *mtx = (dvr_mutex_t*)mutex;
+   int cnt = mtx->lock_cnt;
+   mtx->lock_cnt = 0;
+   mtx->thread = 0;
+   return cnt;
+}
+
+void _dvr_mutex_restore(void *mutex, int val)
+{
+   if (!mutex) {
+       mutex_error("null mutex\n");
+       return;
+   }
+   dvr_mutex_t *mtx = (dvr_mutex_t*)mutex;
+   mtx->lock_cnt = val;
+   mtx->thread = pthread_self();
+}
+
+#ifdef DVR_MUTEX_DEBUG
+void _dvr_mutex_init_dbg(void *mutex, const char *file, int line)
+{
+   mutex_debug("%s:%d\n", file, line);
+   _dvr_mutex_init(mutex);
+}
+void _dvr_mutex_lock_dbg(void *mutex, const char *file, int line)
+{
+   mutex_debug("%s:%d\n", file, line);
+   _dvr_mutex_lock(mutex);
+}
+void _dvr_mutex_unlock_dbg(void *mutex, const char *file, int line)
+{
+   mutex_debug("%s:%d\n", file, line);
+   _dvr_mutex_unlock(mutex);
+}
+void _dvr_mutex_destroy_dbg(void *mutex, const char *file, int line)
+{
+   mutex_debug("%s:%d\n", file, line);
+   _dvr_mutex_destroy(mutex);
+}
+int _dvr_mutex_save_dbg(void *mutex, const char *file, int line)
+{
+   mutex_debug("%s:%d\n", file, line);
+   return _dvr_mutex_save(mutex);
+}
+void _dvr_mutex_restore_dbg(void *mutex, int val, const char *file, int line)
+{
+   mutex_debug("%s:%d\n", file, line);
+   _dvr_mutex_restore(mutex, val);
+}
+#endif
+
diff --git a/src/dvr_playback.c b/src/dvr_playback.c
index c9978c7..60cff30 100644
--- a/src/dvr_playback.c
+++ b/src/dvr_playback.c
@@ -17,8 +17,12 @@
 #include "dvr_playback.h"
 #include "am_crypt.h"
 
-#define DVR_PB_DG(_level, _fmt...) \
-  DVR_DEBUG_FL(_level, "playback", _fmt)
+#define PB_LOG_TAG "libdvr-playback"
+#define DVR_PB_DEBUG(...) DVR_LOG_PRINT(LOG_LV_DEBUG, PB_LOG_TAG, __VA_ARGS__)
+#define DVR_PB_INFO(...) DVR_LOG_PRINT(LOG_LV_INFO, PB_LOG_TAG, __VA_ARGS__)
+#define DVR_PB_WARN(...) DVR_LOG_PRINT(LOG_LV_WARN, PB_LOG_TAG, __VA_ARGS__)
+#define DVR_PB_ERROR(...) DVR_LOG_PRINT(LOG_LV_ERROR, PB_LOG_TAG, __VA_ARGS__)
+#define DVR_PB_FATAL(...) DVR_LOG_PRINT(LOG_LV_FATAL, PB_LOG_TAG, __VA_ARGS__)
 
 #define VALID_PID(_pid_) ((_pid_)>0 && (_pid_)<0x1fff)
 
@@ -32,6 +36,11 @@
 #define IS_KERNEL_SPEED(_SPEED_) (((_SPEED_) == PLAYBACK_SPEED_X2) || ((_SPEED_) == PLAYBACK_SPEED_X1) || ((_SPEED_) == PLAYBACK_SPEED_S2) || ((_SPEED_) == PLAYBACK_SPEED_S4) || ((_SPEED_) == PLAYBACK_SPEED_S8))
 #define IS_FAST_SPEED(_SPEED_) (((_SPEED_) == PLAYBACK_SPEED_X2) || ((_SPEED_) == PLAYBACK_SPEED_S2) || ((_SPEED_) == PLAYBACK_SPEED_S4) || ((_SPEED_) == PLAYBACK_SPEED_S8))
 
+#define DVR_PLAYER_CHANGE_STATE(player,newstate)\
+  DVR_PB_INFO("%s:%d player %p changes state from %s to %s",__func__,__LINE__,\
+    player,_dvr_playback_state_toString(player->state),_dvr_playback_state_toString(newstate));\
+    player->state=newstate;
+
 
 #define FFFB_SLEEP_TIME    (1000)//500ms
 #define FB_DEFAULT_LEFT_TIME    (3000)
@@ -39,7 +48,8 @@
 #define MIN_TSPLAYER_DELAY_TIME (200)
 
 #define MAX_CACHE_TIME    (30000)
-
+//used pcr to control avsync,default not used
+//#define AVSYNC_USED_PCR 1
 static int write_success = 0;
 //
 static int _dvr_playback_fffb(DVR_PlaybackHandle_t handle);
@@ -62,19 +72,19 @@
   char *string[DVR_PLAYBACK_CMD_NONE+1]={
         "start",
         "stop",
-        "vstart",
-        "astart",
-        "vstop",
-        "astop",
-        "vrestart",
-        "arestart",
-        "avrestart",
-        "vstopastart",
-        "astopvstart",
-        "vstoparestart",
-        "astopvrestart",
-        "vstartarestart",
-        "astartvrestart",
+        "v_start",
+        "a_start",
+        "v_stop",
+        "a_stop",
+        "v_restart",
+        "a_restart",
+        "av_restart",
+        "v_stop_a_start",
+        "a_stop_v_start",
+        "v_stop_a_restart",
+        "a_stop_v_restart",
+        "v_start_a_restart",
+        "a_start_v_restart",
         "pause",
         "resume",
         "seek",
@@ -84,28 +94,27 @@
   };
 
   if (cmd > DVR_PLAYBACK_CMD_NONE) {
-    return "unkown";
+    return "unknown";
   } else {
     return string[cmd];
   }
 }
 
 
-static char* _dvr_playback_state_toString(int stat)
+static char* _dvr_playback_state_toString(int state)
 {
-  char *string[DVR_PLAYBACK_STATE_FB+1]={
-        "start",
-        "stop",
-        "pause",
-        "ff",
-        "fb"
+  char *strings[5]={
+        "START",
+        "STOP",
+        "PAUSE",
+        "FF",
+        "FB",
   };
 
-  if (stat > DVR_PLAYBACK_STATE_FB) {
-    return "unkown";
-  } else {
-    return string[stat];
+  if (state >= 5 || state < 0) {
+    return "UNKNOWN";
   }
+  return strings[state];
 }
 
 static DVR_Bool_t _dvr_support_speed(int speed) {
@@ -143,23 +152,24 @@
       ret = DVR_TRUE;
       break;
     default:
-      DVR_PB_DG(1, "not support speed is set [%d]", speed);
+      DVR_PB_INFO("not support speed is set [%d]", speed);
       break;
   }
   return ret;
 }
+
 void _dvr_tsplayer_callback_test(void *user_data, am_tsplayer_event *event)
 {
-  DVR_PB_DG(1, "in callback test ");
+  DVR_PB_INFO("in callback test ");
   DVR_Playback_t *player = NULL;
   if (user_data != NULL) {
     player = (DVR_Playback_t *) user_data;
-    DVR_PB_DG(1, "play speed [%f] in callback test ", player->speed);
+    DVR_PB_INFO("play speed [%f] in callback test ", player->speed);
   }
   switch (event->type) {
       case AM_TSPLAYER_EVENT_TYPE_VIDEO_CHANGED:
       {
-          DVR_PB_DG(1,"[evt] test AM_TSPLAYER_EVENT_TYPE_VIDEO_CHANGED: %d x %d @%d\n",
+          DVR_PB_INFO("[evt] test AM_TSPLAYER_EVENT_TYPE_VIDEO_CHANGED: %d x %d @%d\n",
               event->event.video_format.frame_width,
               event->event.video_format.frame_height,
               event->event.video_format.frame_rate);
@@ -167,7 +177,11 @@
       }
       case AM_TSPLAYER_EVENT_TYPE_FIRST_FRAME:
       {
-          DVR_PB_DG(1, "[evt] test  AM_TSPLAYER_EVENT_TYPE_FIRST_FRAME\n");
+          if (player == NULL) {
+            DVR_PB_WARN("player is null at line %d",__LINE__);
+            break;
+          }
+          DVR_PB_INFO("[evt] test  AM_TSPLAYER_EVENT_TYPE_FIRST_FRAME\n");
           player->first_frame = 1;
           break;
       }
@@ -180,12 +194,12 @@
   DVR_Playback_t *player = NULL;
   if (user_data != NULL) {
     player = (DVR_Playback_t *) user_data;
-    DVR_PB_DG(1, "play speed [%f] in-- callback", player->speed);
+    DVR_PB_INFO("playing speed is [%f] in callback", player->speed);
   }
   switch (event->type) {
     case AM_TSPLAYER_EVENT_TYPE_VIDEO_CHANGED:
     {
-        DVR_PB_DG(1,"[evt] AM_TSPLAYER_EVENT_TYPE_VIDEO_CHANGED: %d x %d @%d\n",
+        DVR_PB_INFO("[evt] AM_TSPLAYER_EVENT_TYPE_VIDEO_CHANGED: %d x %d @%d\n",
             event->event.video_format.frame_width,
             event->event.video_format.frame_height,
             event->event.video_format.frame_rate);
@@ -193,7 +207,11 @@
     }
     case AM_TSPLAYER_EVENT_TYPE_FIRST_FRAME:
     {
-        DVR_PB_DG(1, "[evt] AM_TSPLAYER_EVENT_TYPE_FIRST_FRAME\n");
+        DVR_PB_INFO("[evt] AM_TSPLAYER_EVENT_TYPE_FIRST_FRAME\n");
+        if (player == NULL) {
+          DVR_PB_WARN("player is null at line %d",__LINE__);
+          break;
+        }
         if (player->first_trans_ok == DVR_FALSE) {
           player->first_trans_ok = DVR_TRUE;
           _dvr_playback_sent_transition_ok((DVR_PlaybackHandle_t)player, DVR_FALSE);
@@ -205,28 +223,32 @@
         break;
     }
     case AM_TSPLAYER_EVENT_TYPE_DECODE_FIRST_FRAME_AUDIO:
-        DVR_PB_DG(1, "[evt]AM_TSPLAYER_EVENT_TYPE_DECODE_FIRST_FRAME_AUDIO [%d]\n", event->type);
+        DVR_PB_INFO("[evt]AM_TSPLAYER_EVENT_TYPE_DECODE_FIRST_FRAME_AUDIO [%d]\n", event->type);
+        if (player == NULL) {
+          DVR_PB_WARN("player is null at line %d",__LINE__);
+          break;
+        }
         if (player->first_trans_ok == DVR_FALSE && player->has_video == DVR_FALSE) {
           player->first_trans_ok = DVR_TRUE;
           _dvr_playback_sent_transition_ok((DVR_PlaybackHandle_t)player, DVR_FALSE);
         }
         if (player != NULL && player->has_video == DVR_FALSE) {
-          DVR_PB_DG(1, "[evt]AM_TSPLAYER_EVENT_TYPE_DECODE_FIRST_FRAME_AUDIO [%d]\n", event->type);
+          DVR_PB_INFO("[evt]AM_TSPLAYER_EVENT_TYPE_DECODE_FIRST_FRAME_AUDIO [%d]\n", event->type);
           player->first_frame = 1;
           player->seek_pause = DVR_FALSE;
         }
       break;
     default:
-      DVR_PB_DG(1, "[evt]unkown event [%d]\n", event->type);
+      DVR_PB_INFO("[evt]unknown event [%d]\n", event->type);
       break;
   }
   if (player&&player->player_callback_func) {
-    DVR_PB_DG(1, "player is nonull, --call callback\n");
+    DVR_PB_INFO("calling callback");
     player->player_callback_func(player->player_callback_userdata, event);
   } else if (player == NULL){
-    DVR_PB_DG(1, "player is null, get userdata error\n");
+    DVR_PB_WARN("player pointer %p is invalid",player);
   } else {
-    DVR_PB_DG(1, "player callback is null, get callback error\n");
+    DVR_PB_WARN("player callback function %p is invalid",player->player_callback_func);
   }
 }
 
@@ -303,7 +325,7 @@
   uint32_t s;
   clock_gettime(CLOCK_REALTIME, &ts);
   s = (uint32_t)(ts.tv_sec);
-  DVR_PB_DG(1, "n:%u", s);
+  DVR_PB_INFO("n:%u", s);
   return s;
 }
 
@@ -317,14 +339,14 @@
   return ms;
 }
 
-//timeout wait sibnal
+//timeout wait signal
 static int _dvr_playback_timeoutwait(DVR_PlaybackHandle_t handle , int ms)
 {
   DVR_Playback_t *player = (DVR_Playback_t *) handle;
 
 
   if (player == NULL) {
-    DVR_PB_DG(1, "player is NULL");
+    DVR_PB_INFO("player is NULL");
     return DVR_FAILURE;
   }
 
@@ -340,7 +362,10 @@
   ts.tv_sec += us / 1000000;
   us = us % 1000000;
   ts.tv_nsec = us * 1000;//换算成纳秒
-  pthread_cond_timedwait(&player->cond, &player->lock, &ts);
+
+  int val = dvr_mutex_save(&player->lock);
+  pthread_cond_timedwait(&player->cond, &player->lock.lock, &ts);
+  dvr_mutex_restore(&player->lock, val);
   return 0;
 }
 //get tsplay delay time ms
@@ -348,11 +373,11 @@
   DVR_Playback_t *player = (DVR_Playback_t *) handle;
   int64_t cache = 0;
   if (player == NULL || player->handle == (am_tsplayer_handle)NULL) {
-    DVR_PB_DG(1, "tsplayer delay time error, handle is NULL");
+    DVR_PB_INFO("tsplayer delay time error, handle is NULL");
     return 0;
   }
   AmTsPlayer_getDelayTime(player->handle, &cache);
-  DVR_PB_DG(1, "tsplayer cache time [%lld]ms", cache);
+  DVR_PB_INFO("tsplayer cache time [%lld]ms", cache);
   return cache;
 }
 //send signal
@@ -361,14 +386,14 @@
   DVR_Playback_t *player = (DVR_Playback_t *) handle;\
 
   if (player == NULL) {
-    DVR_PB_DG(1, "player is NULL");
+    DVR_PB_INFO("player is NULL");
     return DVR_FAILURE;
   }
-  DVR_PB_DG(1, "lock---");
-  pthread_mutex_lock(&player->lock);
+  DVR_PB_DEBUG("lock---");
+  dvr_mutex_lock(&player->lock);
   pthread_cond_signal(&player->cond);
-  DVR_PB_DG(1, "unlock---");
-  pthread_mutex_unlock(&player->lock);
+  DVR_PB_DEBUG("unlock---");
+  dvr_mutex_unlock(&player->lock);
   return 0;
 }
 
@@ -378,7 +403,7 @@
   DVR_Playback_t *player = (DVR_Playback_t *) handle;
 
   if (player == NULL) {
-    DVR_PB_DG(1, "player is NULL");
+    DVR_PB_INFO("player is NULL");
     return DVR_FAILURE;
   }
 
@@ -388,7 +413,7 @@
       break;
     case DVR_PLAYBACK_EVENT_TRANSITION_OK:
       //GET STATE
-      DVR_PB_DG(1, "trans ok EVENT");
+      DVR_PB_INFO("trans ok EVENT");
       _dvr_playback_get_status(handle, &(notify->play_status), is_lock);
       break;
     case DVR_PLAYBACK_EVENT_TRANSITION_FAILED:
@@ -399,12 +424,12 @@
       break;
     case DVR_PLAYBACK_EVENT_REACHED_BEGIN:
       //GET STATE
-      DVR_PB_DG(1, "reached begin EVENT");
+      DVR_PB_INFO("reached begin EVENT");
       _dvr_playback_get_status(handle, &(notify->play_status), is_lock);
       break;
     case DVR_PLAYBACK_EVENT_REACHED_END:
       //GET STATE
-      DVR_PB_DG(1, "reached end EVENT");
+      DVR_PB_INFO("reached end EVENT");
       _dvr_playback_get_status(handle, &(notify->play_status), is_lock);
       break;
     case DVR_PLAYBACK_EVENT_NOTIFY_PLAYTIME:
@@ -431,14 +456,14 @@
 {
   DVR_Playback_t *player = (DVR_Playback_t *) handle;
 
+  if (player == NULL) {
+    DVR_PB_ERROR("player is NULL");
+    return DVR_FAILURE;
+  }
   if (player->openParams.is_notify_time == DVR_FALSE) {
     if (CONTROL_SPEED_ENABLE == 0)
        return DVR_SUCCESS;
   }
-  if (player == NULL) {
-    DVR_PB_DG(1, "player is NULL");
-    return DVR_FAILURE;
-  }
 
   if (player->send_time == 0) {
     if (CONTROL_SPEED_ENABLE == 0)
@@ -446,7 +471,12 @@
     else
       player->send_time = _dvr_time_getClock() + 20;
   } else if (player->send_time >= _dvr_time_getClock()) {
-    return DVR_SUCCESS;
+    if ((player->send_time - _dvr_time_getClock()) > 1000) {
+      player->send_time = _dvr_time_getClock() + 500;
+      DVR_PB_INFO("player send time occur system time changed!!!!!");
+    } else {
+      return DVR_SUCCESS;
+    }
   }
   if (CONTROL_SPEED_ENABLE == 0)
     player->send_time = _dvr_time_getClock() + 500;
@@ -465,13 +495,12 @@
 static int _dvr_check_segment_ongoing(DVR_PlaybackHandle_t handle) {
 
   DVR_Playback_t *player = (DVR_Playback_t *) handle;
-  int ret = DVR_FAILURE;
 
   if (player == NULL) {
-    DVR_PB_DG(1, "player is NULL");
+    DVR_PB_INFO("player is NULL");
     return DVR_FAILURE;
   }
-  ret = segment_ongoing(player->r_handle);
+  int ret = segment_ongoing(player->r_handle);
   if (ret != DVR_SUCCESS) {
      return DVR_FALSE;
   }
@@ -482,7 +511,7 @@
 static int _dvr_init_fffb_t(DVR_PlaybackHandle_t handle) {
   DVR_Playback_t *player = (DVR_Playback_t *) handle;
   player->fffb_start = _dvr_time_getClock();
-  DVR_PB_DG(1, " player->fffb_start:%u", player->fffb_start);
+  DVR_PB_INFO(" player->fffb_start:%u", player->fffb_start);
   player->fffb_current = player->fffb_start;
   //get segment current time pos
   player->fffb_start_pcr = _dvr_get_cur_time(handle);
@@ -494,7 +523,7 @@
 static int _dvr_init_fffb_time(DVR_PlaybackHandle_t handle) {
   DVR_Playback_t *player = (DVR_Playback_t *) handle;
   player->fffb_start = _dvr_time_getClock();
-  DVR_PB_DG(1, " player->fffb_start:%u", player->fffb_start);
+  DVR_PB_INFO(" player->fffb_start:%u", player->fffb_start);
   player->fffb_current = player->fffb_start;
   //get segment current time pos
   player->fffb_start_pcr = _dvr_get_cur_time(handle);
@@ -511,12 +540,16 @@
   DVR_PlaybackSegmentInfo_t *pre_segment = NULL;
 
   if (player == NULL) {
-    DVR_PB_DG(1, " player is NULL");
+    DVR_PB_INFO(" player is NULL");
     return DVR_FAILURE;
   }
 
   int found = 0;
   int found_eq_id = 0;
+  // This error is suppressed as the macro code is picked from kernel.
+  // prefetch() here incurring self_assign is used to avoid some compiling
+  // warnings.
+  // coverity[self_assign]
   list_for_each_entry(segment, &player->segment_list, head)
   {
     if (player->segment_is_open == DVR_FALSE) {
@@ -535,7 +568,7 @@
            found = 1;
          } else {
           //not find next id.
-          DVR_PB_DG(1, "not has find next segment on fb mode");
+          DVR_PB_INFO("not has find next segment on fb mode");
           return DVR_FAILURE;
          }
       }
@@ -548,10 +581,10 @@
   }
   if (found != 2) {
     //list is null or reache list  end
-    DVR_PB_DG(1, "not found next segment return failure");
+    DVR_PB_INFO("not found next segment return failure");
     return DVR_FAILURE;
   }
-  DVR_PB_DG(1, "found next segment return success");
+  DVR_PB_INFO("found next segment return success");
   return DVR_SUCCESS;
 }
 
@@ -564,7 +597,7 @@
   uint64_t segmentid;
   uint32_t pos;
   if (player == NULL) {
-    DVR_PB_DG(1, "player is NULL");
+    DVR_PB_INFO("player is NULL");
     return DVR_FAILURE;
   }
 
@@ -574,15 +607,19 @@
     //case cur id < segment id
     if (player->cur_segment_id <= segmentid) {
       //expired ts data is player,return error
-      DVR_PB_DG(1, "reach start segment ,return error");
+      DVR_PB_INFO("reach start segment ,return error");
       return DVR_FAILURE;
     }
-    DVR_PB_DG(1, "has segment to fb play [%lld][%u]", segmentid, pos);
+    DVR_PB_INFO("has segment to fb play [%lld][%u]", segmentid, pos);
   }
 
   int found = 0;
   int found_eq_id = 0;
 
+  // This error is suppressed as the macro code is picked from kernel.
+  // prefetch() here incurring self_assign is used to avoid some compiling
+  // warnings.
+  // coverity[self_assign]
   list_for_each_entry(segment, &player->segment_list, head)
   {
     if (player->segment_is_open == DVR_FALSE) {
@@ -601,7 +638,7 @@
            found = 1;
          } else {
           //not find next id.
-          DVR_PB_DG(1, "not find next segment on fb mode");
+          DVR_PB_INFO("not find next segment on fb mode");
           return DVR_FAILURE;
          }
       }
@@ -614,7 +651,7 @@
       //save segment info
       player->last_segment_id = player->cur_segment_id;
       if (player->r_handle)
-      player->last_segment_tatol = segment_tell_total_time(player->r_handle);
+      player->last_segment_total = segment_tell_total_time(player->r_handle);
       player->last_segment.segment_id = player->cur_segment.segment_id;
       player->last_segment.flags = player->cur_segment.flags;
       memcpy(player->last_segment.location, player->cur_segment.location, DVR_MAX_LOCATION_SIZE);
@@ -626,7 +663,7 @@
       player->cur_segment_id = segment->segment_id;
       player->cur_segment.segment_id = segment->segment_id;
       player->cur_segment.flags = segment->flags;
-      DVR_PB_DG(1, "set cur id cur flag[0x%x]segment->flags flag[0x%x] id [%lld]", player->cur_segment.flags, segment->flags, segment->segment_id);
+      DVR_PB_INFO("set cur id cur flag[0x%x]segment->flags flag[0x%x] id [%lld]", player->cur_segment.flags, segment->flags, segment->segment_id);
       memcpy(player->cur_segment.location, segment->location, DVR_MAX_LOCATION_SIZE);
       //pids
       memcpy(&player->cur_segment.pids, &segment->pids, sizeof(DVR_PlaybackPids_t));
@@ -642,7 +679,7 @@
     player->cur_segment_id = pre_segment->segment_id;
     player->cur_segment.segment_id = pre_segment->segment_id;
     player->cur_segment.flags = pre_segment->flags;
-    DVR_PB_DG(1, "set cur id fb last one cur flag[0x%x]segment->flags flag[0x%x] id [%lld]", player->cur_segment.flags, pre_segment->flags, pre_segment->segment_id);
+    DVR_PB_INFO("set cur id fb last one cur flag[0x%x]segment->flags flag[0x%x] id [%lld]", player->cur_segment.flags, pre_segment->flags, pre_segment->segment_id);
     memcpy(player->cur_segment.location, pre_segment->location, DVR_MAX_LOCATION_SIZE);
     //pids
     memcpy(&player->cur_segment.pids, &pre_segment->pids, sizeof(DVR_PlaybackPids_t));
@@ -662,34 +699,39 @@
   int ret = DVR_SUCCESS;
 
   if (player == NULL) {
-    DVR_PB_DG(1, "player is NULL");
+    DVR_PB_INFO("player is NULL");
     return DVR_FAILURE;
   }
   pthread_mutex_lock(&player->segment_lock);
-
+retry:
   ret = _dvr_get_next_segmentId(handle);
   if (ret == DVR_FAILURE) {
-    DVR_PB_DG(1, "not found segment info");
+    DVR_PB_INFO("not found segment info");
     pthread_mutex_unlock(&player->segment_lock);
     return DVR_FAILURE;
   }
 
   if (player->r_handle != NULL) {
-    DVR_PB_DG(1, "close segment");
+    DVR_PB_INFO("close segment");
     segment_close(player->r_handle);
     player->r_handle = NULL;
   }
 
-  memset(params.location, 0, DVR_MAX_LOCATION_SIZE);
-  //cp chur segment path to location
+  memset((void*)&params,0,sizeof(params));
+  //cp current segment path to location
   memcpy(params.location, player->cur_segment.location, DVR_MAX_LOCATION_SIZE);
   params.segment_id = (uint64_t)player->cur_segment.segment_id;
   params.mode = SEGMENT_MODE_READ;
-  DVR_PB_DG(1, "open segment location[%s]id[%lld]flag[0x%x]", params.location, params.segment_id, player->cur_segment.flags);
+  DVR_PB_INFO("open segment location[%s]id[%lld]flag[0x%x]", params.location, params.segment_id, player->cur_segment.flags);
 
   ret = segment_open(&params, &(player->r_handle));
   if (ret == DVR_FAILURE) {
-    DVR_PB_DG(1, "open segment error");
+    DVR_PB_INFO("open segment error");
+    goto retry;
+  }
+  // Keep the start segment_id when the first segment_open is called during a playback
+  if (player->first_start_id == UINT64_MAX) {
+    player->first_start_id = player->cur_segment.segment_id;
   }
   pthread_mutex_unlock(&player->segment_lock);
   int total = _dvr_get_end_time( handle);
@@ -698,11 +740,11 @@
       //seek end pos -FB_DEFAULT_LEFT_TIME
       player->ts_cache_len = 0;
       segment_seek(player->r_handle, total - FB_DEFAULT_LEFT_TIME, player->openParams.block_size);
-      DVR_PB_DG(1, "seek pos [%d]", total - FB_DEFAULT_LEFT_TIME);
+      DVR_PB_INFO("seek pos [%d]", total - FB_DEFAULT_LEFT_TIME);
   }
   player->dur = total;
   pthread_mutex_unlock(&player->segment_lock);
-  DVR_PB_DG(1, "next segment dur [%d] flag [0x%x]", player->dur, player->cur_segment.flags);
+  DVR_PB_INFO("next segment dur [%d] flag [0x%x]", player->dur, player->cur_segment.flags);
   return ret;
 }
 
@@ -713,67 +755,83 @@
   Segment_OpenParams_t  params;
   int ret = DVR_SUCCESS;
   if (player == NULL) {
-    DVR_PB_DG(1, "player is NULL");
+    DVR_PB_INFO("player is NULL");
     return DVR_FAILURE;
   }
   if (segment_id == player->cur_segment_id && player->segment_is_open == DVR_TRUE) {
     return DVR_SUCCESS;
   }
   uint64_t id = segment_id;
-  if (id < 0) {
-    DVR_PB_DG(1, "not found segment info");
-    return DVR_FAILURE;
-  }
-  DVR_PB_DG(1, "start found segment[%lld]info", id);
+  DVR_PB_INFO("start finding segment[%lld] info", id);
   pthread_mutex_lock(&player->segment_lock);
 
   DVR_PlaybackSegmentInfo_t *segment;
 
   int found = 0;
 
+  // This error is suppressed as the macro code is picked from kernel.
+  // prefetch() here incurring self_assign is used to avoid some compiling
+  // warnings.
+  // coverity[self_assign]
   list_for_each_entry(segment, &player->segment_list, head)
   {
-    DVR_PB_DG(1, "see 1 location [%s]id[%lld]flag[%x]segment_id[%lld]", segment->location, segment->segment_id, segment->flags, segment_id);
+    DVR_PB_INFO("see 1 location [%s]id[%lld]flag[%x]segment_id[%lld]", segment->location, segment->segment_id, segment->flags, segment_id);
     if (segment->segment_id == segment_id) {
       found = 1;
     }
     if (found == 1) {
-      DVR_PB_DG(1, "found  [%s]id[%lld]flag[%x]segment_id[%lld]", segment->location, segment->segment_id, segment->flags, segment_id);
+      DVR_PB_INFO("found  [%s]id[%lld]flag[%x]segment_id[%lld]", segment->location, segment->segment_id, segment->flags, segment_id);
       //get segment info
       player->segment_is_open = DVR_TRUE;
       player->cur_segment_id = segment->segment_id;
       player->cur_segment.segment_id = segment->segment_id;
       player->cur_segment.flags = segment->flags;
-      strncpy(player->cur_segment.location, segment->location, sizeof(segment->location));//DVR_MAX_LOCATION_SIZE
+      const int len = strlen(segment->location);
+      if (len >= DVR_MAX_LOCATION_SIZE || len <= 0) {
+        DVR_PB_ERROR("Invalid segment.location length %d",len);
+        pthread_mutex_unlock(&player->segment_lock);
+        return DVR_FAILURE;
+      }
+      strncpy(player->cur_segment.location, segment->location, len+1);
       //pids
       memcpy(&player->cur_segment.pids, &segment->pids, sizeof(DVR_PlaybackPids_t));
-      DVR_PB_DG(1, "cur found location [%s]id[%lld]flag[%x]", player->cur_segment.location, player->cur_segment.segment_id,player->cur_segment.flags);
+      DVR_PB_INFO("cur found location [%s]id[%lld]flag[%x]", player->cur_segment.location, player->cur_segment.segment_id,player->cur_segment.flags);
       break;
     }
   }
   if (found == 0) {
-    DVR_PB_DG(1, "not found segment info.error..");
+    DVR_PB_INFO("not found segment info.error..");
     pthread_mutex_unlock(&player->segment_lock);
     return DVR_FAILURE;
   }
-  memset(params.location, 0, DVR_MAX_LOCATION_SIZE);
-  //cp cur segment path to location
-  strncpy(params.location, player->cur_segment.location, sizeof(player->cur_segment.location));
+  memset((void*)&params,0,sizeof(params));
+
+  const int len2 = strlen(player->cur_segment.location);
+  if (len2 >= DVR_MAX_LOCATION_SIZE || len2 <= 0) {
+    DVR_PB_ERROR("Invalid cur_segment.location length %d",len2);
+    pthread_mutex_unlock(&player->segment_lock);
+    return DVR_FAILURE;
+  }
+  strncpy(params.location, player->cur_segment.location, len2+1);
   params.segment_id = (uint64_t)player->cur_segment.segment_id;
   params.mode = SEGMENT_MODE_READ;
-  DVR_PB_DG(1, "open segment location[%s][%lld]cur flag[0x%x]", params.location, params.segment_id, player->cur_segment.flags);
+  DVR_PB_INFO("open segment location[%s][%lld]cur flag[0x%x]", params.location, params.segment_id, player->cur_segment.flags);
   if (player->r_handle != NULL) {
     segment_close(player->r_handle);
     player->r_handle = NULL;
   }
   ret = segment_open(&params, &(player->r_handle));
   if (ret == DVR_FAILURE) {
-    DVR_PB_DG(1, "segment opne error");
+    DVR_PB_INFO("segment open error");
+  }
+  // Keep the start segment_id when the first segment_open is called during a playback
+  if (player->first_start_id == UINT64_MAX) {
+    player->first_start_id = player->cur_segment.segment_id;
   }
   pthread_mutex_unlock(&player->segment_lock);
   player->dur = _dvr_get_end_time(handle);
 
-  DVR_PB_DG(1, "player->dur [%d]cur id [%lld]cur flag [0x%x]\r\n", player->dur,player->cur_segment.segment_id, player->cur_segment.flags);
+  DVR_PB_INFO("player->dur [%d]cur id [%lld]cur flag [0x%x]\r\n", player->dur,player->cur_segment.segment_id, player->cur_segment.flags);
   return ret;
 }
 
@@ -781,18 +839,22 @@
 //get play info by segment id
 static int _dvr_playback_get_playinfo(DVR_PlaybackHandle_t handle,
   uint64_t segment_id,
-  am_tsplayer_video_params *vparam,
-  am_tsplayer_audio_params *aparam, am_tsplayer_audio_params *adparam) {
+  am_tsplayer_video_params *video_param,
+  am_tsplayer_audio_params *audio_param, am_tsplayer_audio_params *ad_param) {
 
   DVR_Playback_t *player = (DVR_Playback_t *) handle;
   DVR_PlaybackSegmentInfo_t *segment;
   if (player == NULL) {
-    DVR_PB_DG(1, "player is NULL");
+    DVR_PB_INFO("player is NULL");
     return DVR_FAILURE;
   }
 
   int found = 0;
 
+  // This error is suppressed as the macro code is picked from kernel.
+  // prefetch() here incurring self_assign is used to avoid some compiling
+  // warnings.
+  // coverity[self_assign]
   list_for_each_entry(segment, &player->segment_list, head)
   {
     if (segment_id == UINT64_MAX) {
@@ -806,7 +868,7 @@
       //get segment info
       if (player->cur_segment_id != UINT64_MAX)
         player->cur_segment_id = segment->segment_id;
-      DVR_PB_DG(1, "get play info id [%lld]", player->cur_segment_id);
+      DVR_PB_INFO("get play info id [%lld]", player->cur_segment_id);
       player->cur_segment.segment_id = segment->segment_id;
       player->cur_segment.flags = segment->flags;
       //pids
@@ -821,20 +883,20 @@
       player->cur_segment.pids.ad.type = segment->pids.ad.type;
       player->cur_segment.pids.pcr.pid = segment->pids.pcr.pid;
       //
-      vparam->codectype = _dvr_convert_stream_fmt(segment->pids.video.format, DVR_FALSE);
-      vparam->pid = segment->pids.video.pid;
-      aparam->codectype = _dvr_convert_stream_fmt(segment->pids.audio.format, DVR_TRUE);
-      aparam->pid = segment->pids.audio.pid;
-      adparam->codectype =_dvr_convert_stream_fmt(segment->pids.ad.format, DVR_TRUE);
-      adparam->pid =segment->pids.ad.pid;
-      DVR_PB_DG(1, "get play info sucess[0x%x]apid[0x%x]vfmt[%d]afmt[%d]", vparam->pid, aparam->pid, vparam->codectype, aparam->codectype);
+      video_param->codectype = _dvr_convert_stream_fmt(segment->pids.video.format, DVR_FALSE);
+      video_param->pid = segment->pids.video.pid;
+      audio_param->codectype = _dvr_convert_stream_fmt(segment->pids.audio.format, DVR_TRUE);
+      audio_param->pid = segment->pids.audio.pid;
+      ad_param->codectype =_dvr_convert_stream_fmt(segment->pids.ad.format, DVR_TRUE);
+      ad_param->pid =segment->pids.ad.pid;
+      DVR_PB_INFO("get play info success[0x%x]apid[0x%x]vfmt[%d]afmt[%d]", video_param->pid, audio_param->pid, video_param->codectype, audio_param->codectype);
       found = 2;
       break;
     }
   }
   if (found != 2) {
     //list is null or reache list  end
-    DVR_PB_DG(1, "get play info fail");
+    DVR_PB_INFO("get play info fail");
     return DVR_FAILURE;
   }
 
@@ -843,7 +905,7 @@
 static int _dvr_replay_changed_pid(DVR_PlaybackHandle_t handle) {
   DVR_Playback_t *player = (DVR_Playback_t *) handle;
   if (player == NULL) {
-    DVR_PB_DG(1, "player is NULL");
+    DVR_PB_INFO("player is NULL");
     return DVR_FAILURE;
   }
 
@@ -856,7 +918,7 @@
     _do_check_pid_info(handle, player->last_segment.pids, player->cur_segment.pids, 2);
     //check audio pids stop or restart
     _do_check_pid_info(handle, player->last_segment.pids, player->cur_segment.pids, 1);
-    DVR_PB_DG(1, ":last apid: %d  set apid: %d", player->last_segment.pids.audio.pid,player->cur_segment.pids.audio.pid);
+    DVR_PB_INFO(":last apid: %d  set apid: %d", player->last_segment.pids.audio.pid,player->cur_segment.pids.audio.pid);
     //check pcr pids stop or restart
     _do_check_pid_info(handle, player->last_segment.pids, player->cur_segment.pids, 3);
   }
@@ -867,18 +929,11 @@
 {
   DVR_Playback_t *player = (DVR_Playback_t *) handle;
   if (player == NULL) {
-    DVR_PB_DG(1, "player is NULL");
+    DVR_PB_INFO("player is NULL");
     return DVR_TRUE;
   }
-  char buf[10];
-  dvr_prop_read("vendor.tv.libdvr.con", buf, sizeof(buf));
-  DVR_PB_DG(1, "player get prop[%d][%s]", atoi(buf), buf);
 
-  if (atoi(buf) != 1) {
-    //return DVR_TRUE;
-  }
-
-  DVR_PB_DG(1, ":play speed: %f  ply dur: %u sys_dur: %u",
+  DVR_PB_INFO(":play speed: %f  ply dur: %u sys_dur: %u",
                 player->speed,
                 player->con_spe.ply_dur,
                 player->con_spe.sys_dur);
@@ -897,14 +952,14 @@
 {
   DVR_Playback_t *player = (DVR_Playback_t *) handle;
   if (player == NULL) {
-    DVR_PB_DG(1, "player is NULL");
+    DVR_PB_INFO("player is NULL");
     return DVR_FAILURE;
   }
   if (player->vendor == DVR_PLAYBACK_VENDOR_AML) {
-    DVR_PB_DG(1, "vendor is amlogic. no used segment flag to hide or show av");
+    DVR_PB_INFO("vendor is amlogic. no used segment flag to hide or show av");
     return DVR_SUCCESS;
   }
-  DVR_PB_DG(1, "flag[0x%x]id[%lld]last[0x%x][%llu]",
+  DVR_PB_INFO("flag[0x%x]id[%lld]last[0x%x][%llu]",
                 player->cur_segment.flags,
                 player->cur_segment.segment_id,
                 player->last_segment.flags,
@@ -912,27 +967,27 @@
   if ((player->cur_segment.flags & DVR_PLAYBACK_SEGMENT_DISPLAYABLE) == DVR_PLAYBACK_SEGMENT_DISPLAYABLE &&
     (player->last_segment.flags & DVR_PLAYBACK_SEGMENT_DISPLAYABLE) == 0) {
     //enable display
-    DVR_PB_DG(1, "unmute");
+    DVR_PB_INFO("unmute");
     AmTsPlayer_showVideo(player->handle);
     AmTsPlayer_setAudioMute(player->handle, 0, 0);
   } else if ((player->cur_segment.flags & DVR_PLAYBACK_SEGMENT_DISPLAYABLE) == 0 &&
     (player->last_segment.flags & DVR_PLAYBACK_SEGMENT_DISPLAYABLE) == DVR_PLAYBACK_SEGMENT_DISPLAYABLE) {
     //disable display
-    DVR_PB_DG(1, "mute");
+    DVR_PB_INFO("mute");
     AmTsPlayer_hideVideo(player->handle);
     AmTsPlayer_setAudioMute(player->handle, 1, 1);
   }
   return DVR_SUCCESS;
 }
 /*
-if decodec sucess first time.
-sucess:  return true
+if decode success first time.
+success:  return true
 fail:    return false
 */
-static DVR_Bool_t _dvr_pauselive_decode_sucess(DVR_PlaybackHandle_t handle) {
+static DVR_Bool_t _dvr_pauselive_decode_success(DVR_PlaybackHandle_t handle) {
   DVR_Playback_t *player = (DVR_Playback_t *) handle;
   if (player == NULL) {
-    DVR_PB_DG(1, "player is NULL");
+    DVR_PB_INFO("player is NULL");
     return DVR_TRUE;
   }
   if (player->first_frame == 1) {
@@ -945,48 +1000,43 @@
 {
   DVR_Playback_t *player = (DVR_Playback_t *) arg;
   //int need_open_segment = 1;
-  am_tsplayer_input_buffer     wbufs;
+  am_tsplayer_input_buffer     input_buffer;
   am_tsplayer_input_buffer     dec_bufs;
   int ret = DVR_SUCCESS;
 
   #define MAX_REACHEND_TIMEOUT (3000)
   int reach_end_timeout = 0;//ms
   int cache_time = 0;
-  int timeout = 100;//ms
   int check_no_data_time = 4;
-  uint64_t write_timeout_ms = 50;
-  uint8_t *buf = NULL;
   int buf_len = player->openParams.block_size > 0 ? player->openParams.block_size : (256 * 1024);
   DVR_Bool_t b_writed_whole_block = player->openParams.block_size > 0 ? DVR_TRUE:DVR_FALSE;
   int first_write = 0;
   int dec_buf_size = buf_len + 188;
   int real_read = 0;
   DVR_Bool_t goto_rewrite = DVR_FALSE;
-  char prop_buf[10];
+  int read = 0;
 
-  memset(prop_buf, 0 ,sizeof(prop_buf));
-  dvr_prop_read("vendor.tv.libdvr.writetm", prop_buf, sizeof(prop_buf));
-  DVR_PB_DG(1, "---vendor.tv.libdvr.writetm get prop[%d][%s]block_size[%d]", atoi(prop_buf), prop_buf, player->openParams.block_size);
-  if (atoi(prop_buf) > 0)
-    write_timeout_ms = atoi(prop_buf);
+  const uint64_t write_timeout_ms = (uint64_t)dvr_prop_read_int("vendor.tv.libdvr.writetm",50);
+  const int timeout = dvr_prop_read_int("vendor.tv.libdvr.waittm",200);
 
   if (player->is_secure_mode) {
     if (dec_buf_size > player->secure_buffer_size) {
-      DVR_PB_DG(1, "playback blocksize too large");
+      DVR_PB_INFO("playback blocksize too large");
       return NULL;
     }
   }
-  buf = malloc(buf_len);
+
+  uint8_t *buf = malloc(buf_len);
   if (!buf) {
-    DVR_PB_DG(1, "Malloc buffer failed");
+    DVR_PB_INFO("Malloc buffer failed");
     return NULL;
   }
-  wbufs.buf_type = TS_INPUT_BUFFER_TYPE_NORMAL;
-  wbufs.buf_size = 0;
+  input_buffer.buf_type = TS_INPUT_BUFFER_TYPE_NORMAL;
+  input_buffer.buf_size = 0;
 
   dec_bufs.buf_data = malloc(dec_buf_size);
   if (!dec_bufs.buf_data) {
-    DVR_PB_DG(1, "Malloc dec buffer failed");
+    DVR_PB_INFO("Malloc dec buffer failed");
     free(buf);
     return NULL;
   }
@@ -1000,13 +1050,12 @@
   if (ret != DVR_SUCCESS) {
     if (buf != NULL) {
       free(buf);
-      buf = NULL;
     }
     free(dec_bufs.buf_data);
-    DVR_PB_DG(1, "get segment error");
+    DVR_PB_INFO("get segment error");
     return NULL;
   }
-  DVR_PB_DG(1, "--player->vendor %d,player->has_video[%d] bufsize[0x%x]whole block[%d]",
+  DVR_PB_INFO("--player->vendor %d,player->has_video[%d] bufsize[0x%x]whole block[%d]",
                 player->vendor, player->has_video, buf_len, b_writed_whole_block);
   //get play statue not here,send ok event when vendor is aml or only audio channel if not send ok event
   if (((player->first_trans_ok == DVR_FALSE) && (player->vendor == DVR_PLAYBACK_VENDOR_AML) ) ||
@@ -1023,8 +1072,48 @@
   while (player->is_running/* || player->cmd.last_cmd != player->cmd.cur_cmd*/) {
 
     //check trick stat
-    DVR_PB_DG(1, "lock check_no_data_time:%d", check_no_data_time);
-    pthread_mutex_lock(&player->lock);
+    //DVR_PB_INFO("lock check_no_data_time:%d", check_no_data_time);
+    dvr_mutex_lock(&player->lock);
+
+    {
+      static struct timespec _prev_ts={0,0};
+      struct timespec _nowts,_diffts;
+      clock_gettime(CLOCK_MONOTONIC, &_nowts);
+      clock_timespec_subtract(&_nowts,&_prev_ts,&_diffts);
+      if (_diffts.tv_sec>0) {
+        char _logbuf[512]={0};
+        char* _pbuf=_logbuf;
+        int _nchar=0;
+        DVR_PlaybackSegmentInfo_t* _segment;
+        // This error is suppressed as the macro code is picked from kernel.
+        // prefetch() here incurring self_assign is used to avoid some compiling
+        // warnings.
+        // coverity[self_assign]
+        list_for_each_entry(_segment, &player->segment_list, head) {
+          if (player->cur_segment_id == _segment->segment_id) {
+            int seg_size = segment_get_cur_segment_size(player->r_handle);
+            int read_ptr = segment_tell_position(player->r_handle);
+            float progress = -1.0f;
+            if (seg_size>0) {
+                progress = (float)read_ptr*100/seg_size;
+            }
+            _nchar=sprintf(_pbuf,"%lld(%.1f%%), ",_segment->segment_id,progress);
+          } else {
+            _nchar=sprintf(_pbuf,"%lld, ",_segment->segment_id);
+          }
+          if (_nchar<0) {
+            break;
+          }
+          _pbuf+=_nchar;
+          if (_pbuf-_logbuf+10 >= sizeof(_logbuf)) {
+            sprintf(_pbuf,"...");
+            break;
+          }
+        }
+        DVR_PB_INFO("clk: %08u, seg_list: %s",_nowts.tv_sec,_logbuf);
+        _prev_ts=_nowts;
+      }
+    }
 
     if (player->cmd.cur_cmd == DVR_PLAYBACK_CMD_SEEK ||
       player->cmd.cur_cmd == DVR_PLAYBACK_CMD_FF ||
@@ -1035,22 +1124,22 @@
     {
       trick_stat = _dvr_playback_get_trick_stat((DVR_PlaybackHandle_t)player);
       if (trick_stat > 0) {
-        DVR_PB_DG(1, "trick stat[%d] is > 0 cur cmd[%d]last cmd[%d]flag[0x%x]",
+        DVR_PB_INFO("trick stat[%d] is > 0 cur cmd[%d]last cmd[%d]flag[0x%x]",
                       trick_stat, player->cmd.cur_cmd, player->cmd.last_cmd, player->play_flag);
         if (player->cmd.cur_cmd == DVR_PLAYBACK_CMD_SEEK || (player->play_flag&DVR_PLAYBACK_STARTED_PAUSEDLIVE) == DVR_PLAYBACK_STARTED_PAUSEDLIVE) {
           //check last cmd
           if (player->cmd.last_cmd == DVR_PLAYBACK_CMD_PAUSE
             || ((player->play_flag&DVR_PLAYBACK_STARTED_PAUSEDLIVE) == DVR_PLAYBACK_STARTED_PAUSEDLIVE
                 && ( player->cmd.cur_cmd == DVR_PLAYBACK_CMD_START
-                ||player->cmd.last_cmd == DVR_PLAYBACK_CMD_VSTART
-                    || player->cmd.last_cmd == DVR_PLAYBACK_CMD_ASTART
+                ||player->cmd.last_cmd == DVR_PLAYBACK_CMD_V_START
+                    || player->cmd.last_cmd == DVR_PLAYBACK_CMD_A_START
                     || player->cmd.last_cmd == DVR_PLAYBACK_CMD_START))) {
-            DVR_PB_DG(1, "pause play-------cur cmd[%d]last cmd[%d]flag[0x%x]",
+            DVR_PB_INFO("pause play-------cur cmd[%d]last cmd[%d]flag[0x%x]",
                           player->cmd.cur_cmd, player->cmd.last_cmd, player->play_flag);
             //need change to pause state
             player->cmd.cur_cmd = DVR_PLAYBACK_CMD_PAUSE;
             player->cmd.state = DVR_PLAYBACK_STATE_PAUSE;
-            player->state = DVR_PLAYBACK_STATE_PAUSE;
+            DVR_PLAYER_CHANGE_STATE(player,DVR_PLAYBACK_STATE_PAUSE);
             //clear flag
             player->play_flag = player->play_flag & (~DVR_PLAYBACK_STARTED_PAUSEDLIVE);
             player->first_frame = 0;
@@ -1058,7 +1147,7 @@
             AmTsPlayer_pauseVideoDecoding(player->handle);
             AmTsPlayer_pauseAudioDecoding(player->handle);
           } else {
-            DVR_PB_DG(1, "clear first frame value-------");
+            DVR_PB_INFO("clear first frame value-------");
             player->first_frame = 0;
           }
         } else if (player->cmd.cur_cmd == DVR_PLAYBACK_CMD_FF
@@ -1066,55 +1155,56 @@
                 ||player->speed > FF_SPEED ||player->speed < FB_SPEED) {
             //restart play stream if speed > 2
             if (player->state == DVR_PLAYBACK_STATE_PAUSE) {
-              DVR_PB_DG(1, "fffb pause state----speed[%f] fffb cur[%u] cur sys[%u] [%s] [%u]",
+              DVR_PB_INFO("fffb pause state----speed[%f] fffb cur[%u] cur sys[%u] [%s] [%u]",
                             player->speed,
                             player->fffb_current,
                             _dvr_time_getClock(),
                             _dvr_playback_state_toString(player->state),
                             player->next_fffb_time);
               //used timeout wait need lock first,so we unlock and lock
-              //pthread_mutex_unlock(&player->lock);
-              //pthread_mutex_lock(&player->lock);
+              //dvr_mutex_unlock(&player->lock);
+              //dvr_mutex_lock(&player->lock);
               _dvr_playback_timeoutwait((DVR_PlaybackHandle_t)player, timeout);
-                DVR_PB_DG(1, "unlock---");
-              pthread_mutex_unlock(&player->lock);
+              DVR_PB_DEBUG("unlock---");
+              dvr_mutex_unlock(&player->lock);
               continue;
             } else if (_dvr_time_getClock() < player->next_fffb_time) {
-              DVR_PB_DG(1, "fffb timeout-to pause video---speed[%f] fffb cur[%u] cur sys[%u] [%s] [%u]",
+              DVR_PB_INFO("fffb timeout-to pause video---speed[%f] fffb cur[%u] cur sys[%u] [%s] [%u]",
                             player->speed,
                             player->fffb_current,
                             _dvr_time_getClock(),
                             _dvr_playback_state_toString(player->state),
                             player->next_fffb_time);
               //used timeout wait need lock first,so we unlock and lock
-              //pthread_mutex_unlock(&player->lock);
-              //pthread_mutex_lock(&player->lock);
+              //dvr_mutex_unlock(&player->lock);
+              //dvr_mutex_lock(&player->lock);
               AmTsPlayer_pauseVideoDecoding(player->handle);
               _dvr_playback_timeoutwait((DVR_PlaybackHandle_t)player, timeout);
-                DVR_PB_DG(1, "unlock---");
-              pthread_mutex_unlock(&player->lock);
+              DVR_PB_DEBUG("unlock---");
+              dvr_mutex_unlock(&player->lock);
               continue;
             }
-            DVR_PB_DG(1, "fffb play-------speed[%f][%d][%d][%s][%d]",
+            DVR_PB_INFO("fffb play-------speed[%f][%d][%d][%s][%d]",
                         player->speed,
                         goto_rewrite,
                         real_read,
                         _dvr_playback_state_toString(player->state),
                         player->cmd.cur_cmd);
-            DVR_PB_DG(1, "unlock---");
-            pthread_mutex_unlock(&player->lock);
             goto_rewrite = DVR_FALSE;
             real_read = 0;
             player->play_flag = player->play_flag & (~DVR_PLAYBACK_STARTED_PAUSEDLIVE);
             player->first_frame = 0;
+            DVR_PB_INFO("unlock---");
+            dvr_mutex_unlock(&player->lock);
+
             _dvr_playback_fffb((DVR_PlaybackHandle_t)player);
+            DVR_PB_DEBUG("lock---");
+            dvr_mutex_lock(&player->lock);
             player->fffb_play = DVR_FALSE;
-            DVR_PB_DG(1, "lock---");
-            pthread_mutex_lock(&player->lock);
         } else if(player->state == DVR_PLAYBACK_STATE_PAUSE) {
             //on pause state,user seek to new pos,we need pause and wait
             //user to resume
-            DVR_PB_DG(1, "pause, when got first frame event when user seek end");
+            DVR_PB_INFO("pause, when got first frame event when user seek end");
             player->first_frame = 0;
             AmTsPlayer_setTrickMode(player->handle, AV_VIDEO_TRICK_MODE_NONE);
             AmTsPlayer_pauseVideoDecoding(player->handle);
@@ -1124,36 +1214,38 @@
         //for first into fffb when reset speed
         if (player->state == DVR_PLAYBACK_STATE_PAUSE ||
           _dvr_time_getClock() < player->next_fffb_time) {
-          DVR_PB_DG(1, "fffb timeout-fffb play---speed[%f] fffb cur[%u] cur sys[%u] [%s] [%u]",
+          DVR_PB_INFO("fffb timeout-fffb play---speed[%f] fffb cur[%u] cur sys[%u] [%s] [%u]",
                         player->speed,
                         player->fffb_current,
                         _dvr_time_getClock(),
                         _dvr_playback_state_toString(player->state),
                         player->next_fffb_time);
           //used timeout wait need lock first,so we unlock and lock
-          //pthread_mutex_unlock(&player->lock);
-          //pthread_mutex_lock(&player->lock);
+          //dvr_mutex_unlock(&player->lock);
+          //dvr_mutex_lock(&player->lock);
           _dvr_playback_timeoutwait((DVR_PlaybackHandle_t)player, timeout);
-          DVR_PB_DG(1, "unlock---");
-          pthread_mutex_unlock(&player->lock);
+          DVR_PB_DEBUG("unlock---");
+          dvr_mutex_unlock(&player->lock);
           continue;
         }
-        DVR_PB_DG(1, "fffb replay-------speed[%f][%d][%d][%s][%d]player->fffb_play[%d]",
+        DVR_PB_INFO("fffb replay-------speed[%f][%d][%d][%s][%d]player->fffb_play[%d]",
                       player->speed,
                       goto_rewrite,
                       real_read,
                       _dvr_playback_state_toString(player->state),
                       player->cmd.cur_cmd,
                       player->fffb_play);
-          DVR_PB_DG(1, "unlock---");
-        pthread_mutex_unlock(&player->lock);
+        DVR_PB_DEBUG("unlock---");
+        dvr_mutex_unlock(&player->lock);
         goto_rewrite = DVR_FALSE;
         real_read = 0;
+        pthread_mutex_lock(&player->segment_lock);
         player->ts_cache_len = 0;
         player->play_flag = player->play_flag & (~DVR_PLAYBACK_STARTED_PAUSEDLIVE);
         player->first_frame = 0;
+        pthread_mutex_unlock(&player->segment_lock);
         _dvr_playback_fffb((DVR_PlaybackHandle_t)player);
-        pthread_mutex_lock(&player->lock);
+        dvr_mutex_lock(&player->lock);
         player->fffb_play = DVR_FALSE;
       }
     }
@@ -1161,14 +1253,14 @@
     if (player->state == DVR_PLAYBACK_STATE_PAUSE
         && player->seek_pause == DVR_FALSE) {
       //check is need send time send end
-      DVR_PB_DG(1, "pause, continue");
-      DVR_PB_DG(1, "unlock---");
-      pthread_mutex_unlock(&player->lock);
+      DVR_PB_INFO("pause, continue");
+      DVR_PB_DEBUG("unlock---");
+      dvr_mutex_unlock(&player->lock);
       _dvr_playback_sent_playtime((DVR_PlaybackHandle_t)player, DVR_FALSE);
-      pthread_mutex_lock(&player->lock);
+      dvr_mutex_lock(&player->lock);
       _dvr_playback_timeoutwait((DVR_PlaybackHandle_t)player, timeout);
-      DVR_PB_DG(1, "unlock---");
-      pthread_mutex_unlock(&player->lock);
+      DVR_PB_DEBUG("unlock---");
+      dvr_mutex_unlock(&player->lock);
       continue;
     }
     //when seek action is done. we need drop write timeout data.
@@ -1179,28 +1271,28 @@
     }
     if (goto_rewrite == DVR_TRUE) {
       goto_rewrite = DVR_FALSE;
-        DVR_PB_DG(1, "unlock---");
-
-      pthread_mutex_unlock(&player->lock);
-      //DVR_PB_DG(1, "rewrite-player->speed[%f]", player->speed);
+      //DVR_PB_DEBUG("unlock---");
+      dvr_mutex_unlock(&player->lock);
+      _dvr_playback_sent_playtime((DVR_PlaybackHandle_t)player, DVR_FALSE);
+      //DVR_PB_INFO("rewrite-player->speed[%f]", player->speed);
       goto rewrite;
     }
     //.check is need send time send end
-    pthread_mutex_unlock(&player->lock);
+    dvr_mutex_unlock(&player->lock);
     _dvr_playback_sent_playtime((DVR_PlaybackHandle_t)player, DVR_FALSE);
-    pthread_mutex_lock(&player->lock);
+    dvr_mutex_lock(&player->lock);
     pthread_mutex_lock(&player->segment_lock);
-    //DVR_PB_DG(1, "start read");
-    int read = segment_read(player->r_handle, buf + real_read, buf_len - real_read);
+    //DVR_PB_INFO("start read");
+    read = segment_read(player->r_handle, buf + real_read, buf_len - real_read);
     real_read = real_read + read;
     player->ts_cache_len = real_read;
-    //DVR_PB_DG(1, "start read end [%d]", read);
+    //DVR_PB_INFO("start read end [%d]", read);
     pthread_mutex_unlock(&player->segment_lock);
-    DVR_PB_DG(1, "unlock---");
-    pthread_mutex_unlock(&player->lock);
+    //DVR_PB_DEBUG("unlock---");
+    dvr_mutex_unlock(&player->lock);
     if (read < 0 && errno == EIO) {
       //EIO ERROR, EXIT THRAD
-      DVR_PB_DG(1, "read error.EIO error, exit thread");
+      DVR_PB_INFO("read error.EIO error, exit thread");
       DVR_Play_Notify_t notify;
       memset(&notify, 0 , sizeof(DVR_Play_Notify_t));
       notify.event = DVR_PLAYBACK_EVENT_ERROR;
@@ -1208,41 +1300,39 @@
       _dvr_playback_sent_event((DVR_PlaybackHandle_t)player,DVR_PLAYBACK_EVENT_ERROR, &notify, DVR_TRUE);
       goto end;
     } else if (read < 0) {
-      DVR_PB_DG(1, "read error.:%d EIO:%d", errno, EIO);
+      DVR_PB_INFO("read error.:%d EIO:%d", errno, EIO);
     }
     //if on fb mode and read file end , we need calculate pos to retry read.
     if (read == 0 && IS_FB(player->speed) && real_read == 0) {
-      DVR_PB_DG(1, "recalculate read [%d] readed [%d]buf_len[%d]speed[%f]id=[%llu]",
+      DVR_PB_INFO("recalculate read [%d] readed [%d]buf_len[%d]speed[%f]id=[%llu]",
                     read,
                     real_read,
                     buf_len,
                     player->speed,
                     player->cur_segment_id);
       _dvr_playback_calculate_seekpos((DVR_PlaybackHandle_t)player);
-        DVR_PB_DG(1, "lock---");
-      pthread_mutex_lock(&player->lock);
+      DVR_PB_DEBUG("lock---");
+      dvr_mutex_lock(&player->lock);
       _dvr_playback_timeoutwait((DVR_PlaybackHandle_t)player, timeout);
-        DVR_PB_DG(1, "unlock---");
-      pthread_mutex_unlock(&player->lock);
+      DVR_PB_DEBUG("unlock---");
+      dvr_mutex_unlock(&player->lock);
       continue;
     }
-    //DVR_PB_DG(1, "read ts [%d]buf_len[%d]speed[%f]real_read:%d", read, buf_len, player->speed, real_read);
+    //DVR_PB_INFO("read ts [%d]buf_len[%d]speed[%f]real_read:%d", read, buf_len, player->speed, real_read);
     if (read == 0) {
       //file end.need to play next segment
       #define MIN_CACHE_TIME (3000)
       int _cache_time = _dvr_playback_get_delaytime((DVR_PlaybackHandle_t)player) ;
       /*if cache time is > min cache time ,not read next segment,wait cache data to play*/
       if (_cache_time > MIN_CACHE_TIME) {
-        //pthread_mutex_lock(&player->lock);
+        //dvr_mutex_lock(&player->lock);
         /*if cache time > 20s , we think get time is error,*/
         if (_cache_time - MIN_CACHE_TIME > 20 * 1000) {
-            DVR_PB_DG(1, "read end but cache time is %d > 20s, this is an error at media_hal", _cache_time);
-            DVR_PB_DG(1, "read end but cache time is %d > 20s, this is an error at media_hal", _cache_time);
-            DVR_PB_DG(1, "read end but cache time is %d > 20s, this is an error at media_hal", _cache_time);
+            DVR_PB_WARN("read end but cache time is %d > 20s, this is an error at media_hal", _cache_time);
         }
         //_dvr_playback_timeoutwait((DVR_PlaybackHandle_t)player, ((_cache_time - MIN_CACHE_TIME) > MIN_CACHE_TIME ? MIN_CACHE_TIME : (_cache_time - MIN_CACHE_TIME)));
-        //pthread_mutex_unlock(&player->lock);
-       // DVR_PB_DG(1, "read end but cache time is %d > %d, to sleep end and continue", _cache_time, MIN_CACHE_TIME);
+        //dvr_mutex_unlock(&player->lock);
+       // DVR_PB_INFO("read end but cache time is %d > %d, to sleep end and continue", _cache_time, MIN_CACHE_TIME);
         //continue;
       }
 
@@ -1254,14 +1344,14 @@
 
       if (ret != DVR_SUCCESS && delay < MIN_TSPLAYER_DELAY_TIME) {
         player->noData++;
-        DVR_PB_DG(1, "playback nodata[%d]", player->noData);
+        DVR_PB_INFO("playback nodata[%d]", player->noData);
         if (player->noData == check_no_data_time) {
-            DVR_PB_DG(1, "playback send nodata event nodata[%d]", player->noData);
+            DVR_PB_INFO("playback send nodata event nodata[%d]", player->noData);
                   //send event here and pause
             DVR_Play_Notify_t notify;
             memset(&notify, 0 , sizeof(DVR_Play_Notify_t));
             notify.event = DVR_PLAYBACK_EVENT_NODATA;
-            DVR_PB_DG(1, "send event DVR_PLAYBACK_EVENT_NODATA--");
+            DVR_PB_INFO("send event DVR_PLAYBACK_EVENT_NODATA--");
             //get play statue not here
             _dvr_playback_sent_event((DVR_PlaybackHandle_t)player, DVR_PLAYBACK_EVENT_NODATA, &notify, DVR_FALSE);
         }
@@ -1271,7 +1361,7 @@
         (player->vendor != DVR_PLAYBACK_VENDOR_AMAZON) &&
         (delay <= MIN_TSPLAYER_DELAY_TIME ||
           player->cmd.cur_cmd == DVR_PLAYBACK_CMD_FF) &&
-        _dvr_pauselive_decode_sucess((DVR_PlaybackHandle_t)player)) ||
+        _dvr_pauselive_decode_success((DVR_PlaybackHandle_t)player)) ||
         (reach_end_timeout >= MAX_REACHEND_TIMEOUT )) {
          //send end event to hal
          DVR_Play_Notify_t notify;
@@ -1281,16 +1371,16 @@
          dvr_playback_pause((DVR_PlaybackHandle_t)player, DVR_FALSE);
          _dvr_playback_sent_event((DVR_PlaybackHandle_t)player, DVR_PLAYBACK_EVENT_REACHED_END, &notify, DVR_TRUE);
          //continue,timeshift mode, when read end,need wait cur recording segment
-         DVR_PB_DG(1, "playback is  send end delay:[%d]reach_end_timeout[%d]ms", delay, reach_end_timeout);
-         pthread_mutex_lock(&player->lock);
+         DVR_PB_INFO("playback is  send end delay:[%d]reach_end_timeout[%d]ms", delay, reach_end_timeout);
+         dvr_mutex_lock(&player->lock);
          _dvr_playback_timeoutwait((DVR_PlaybackHandle_t)player, timeout);
-         pthread_mutex_unlock(&player->lock);
+         dvr_mutex_unlock(&player->lock);
          continue;
        } else if (ret != DVR_SUCCESS) {
-          DVR_PB_DG(1, "delay:%d pauselive:%d", delay, _dvr_pauselive_decode_sucess((DVR_PlaybackHandle_t)player));
-         pthread_mutex_lock(&player->lock);
+         DVR_PB_INFO("delay:%d pauselive:%d", delay, _dvr_pauselive_decode_success((DVR_PlaybackHandle_t)player));
+         dvr_mutex_lock(&player->lock);
          _dvr_playback_timeoutwait((DVR_PlaybackHandle_t)player, timeout);
-         pthread_mutex_unlock(&player->lock);
+         dvr_mutex_unlock(&player->lock);
          delay = _dvr_playback_get_delaytime((DVR_PlaybackHandle_t)player);
          //not send event and pause,sleep and go to next time to recheck
          if (delay < cache_time) {
@@ -1306,9 +1396,9 @@
       cache_time = 0;
       //change next segment success case
       _dvr_playback_sent_transition_ok((DVR_PlaybackHandle_t)player, DVR_FALSE);
-      pthread_mutex_lock(&player->lock);
+      dvr_mutex_lock(&player->lock);
       player->noData = 0;
-      DVR_PB_DG(1, "_dvr_replay_changed_pid:start");
+      DVR_PB_INFO("_dvr_replay_changed_pid:start");
       _dvr_replay_changed_pid((DVR_PlaybackHandle_t)player);
       _dvr_check_cur_segment_flag((DVR_PlaybackHandle_t)player);
       pthread_mutex_lock(&player->segment_lock);
@@ -1317,137 +1407,163 @@
       player->ts_cache_len = real_read;
       pthread_mutex_unlock(&player->segment_lock);
 
-      pthread_mutex_unlock(&player->lock);
+      dvr_mutex_unlock(&player->lock);
     }//read len 0 check end
     if (player->noData >= check_no_data_time) {
       player->noData = 0;
-      DVR_PB_DG(1, "playback send data event resume[%d]", player->noData);
+      DVR_PB_INFO("playback send data event resume[%d]", player->noData);
       //send event here and pause
       DVR_Play_Notify_t notify;
       memset(&notify, 0 , sizeof(DVR_Play_Notify_t));
       notify.event = DVR_PLAYBACK_EVENT_DATARESUME;
-      DVR_PB_DG(1, "----send event DVR_PLAYBACK_EVENT_DATARESUME");
+      DVR_PB_INFO("----send event DVR_PLAYBACK_EVENT_DATARESUME");
       //get play statue not here
       _dvr_playback_sent_event((DVR_PlaybackHandle_t)player, DVR_PLAYBACK_EVENT_DATARESUME, &notify, DVR_FALSE);
     }
     reach_end_timeout = 0;
     //real_read = real_read + read;
-    wbufs.buf_size = real_read;
-    wbufs.buf_data = buf;
+    input_buffer.buf_size = real_read;
+    input_buffer.buf_data = buf;
 
-    //check read data len,iflen < 0, we need continue
-    if (wbufs.buf_size <= 0 || wbufs.buf_data == NULL) {
-      DVR_PB_DG(1, "error occur read_read [%d],buf=[%p]",wbufs.buf_size, wbufs.buf_data);
+    //check read data len,if len < 0, we need continue
+    if (input_buffer.buf_size <= 0 || input_buffer.buf_data == NULL) {
+      DVR_PB_INFO("error occur read_read [%d],buf=[%p]",input_buffer.buf_size, input_buffer.buf_data);
       real_read = 0;
+      pthread_mutex_lock(&player->segment_lock);
       player->ts_cache_len = 0;
+      pthread_mutex_unlock(&player->segment_lock);
       continue;
     }
     //if need write whole block size, we need check read buf len is eq block size.
     if (b_writed_whole_block == DVR_TRUE) {
       //buf_len is block size value.
       if (real_read < buf_len) {
-        //coontinue to read data from file
-        DVR_PB_DG(1, "read buf len[%d] is < block size [%d]", real_read, buf_len);
-        pthread_mutex_lock(&player->lock);
-         _dvr_playback_timeoutwait((DVR_PlaybackHandle_t)player, timeout);
-         pthread_mutex_unlock(&player->lock);
-         DVR_PB_DG(1, "read buf len[%d] is < block size [%d] continue", real_read, buf_len);
+        //continue to read data from file
+        DVR_PB_INFO("read buf len[%d] is < block size [%d]", real_read, buf_len);
+        dvr_mutex_lock(&player->lock);
+        _dvr_playback_timeoutwait((DVR_PlaybackHandle_t)player, timeout);
+        dvr_mutex_unlock(&player->lock);
+        DVR_PB_INFO("read buf len[%d] is < block size [%d] continue", real_read, buf_len);
         continue;
       } else if (real_read > buf_len) {
-        DVR_PB_DG(1, "read buf len[%d] is > block size [%d],this error occur", real_read, buf_len);
+        DVR_PB_INFO("read buf len[%d] is > block size [%d],this error occur", real_read, buf_len);
       }
     }
 
-    if (player->is_secure_mode && player->dec_func) {
+    if (player->dec_func) {
       DVR_CryptoParams_t crypto_params;
 
       memset(&crypto_params, 0, sizeof(crypto_params));
       crypto_params.type = DVR_CRYPTO_TYPE_DECRYPT;
       memcpy(crypto_params.location, player->cur_segment.location, strlen(player->cur_segment.location));
       crypto_params.segment_id = player->cur_segment.segment_id;
-      crypto_params.offset = segment_tell_position(player->r_handle) - wbufs.buf_size;
+      crypto_params.offset = segment_tell_position(player->r_handle) - input_buffer.buf_size;
       if ((crypto_params.offset % (player->openParams.block_size)) != 0)
-        DVR_PB_DG(1, "offset is not block_size %d", player->openParams.block_size);
+        DVR_PB_INFO("offset is not block_size %d", player->openParams.block_size);
       crypto_params.input_buffer.type = DVR_BUFFER_TYPE_NORMAL;
       crypto_params.input_buffer.addr = (size_t)buf;
       crypto_params.input_buffer.size = real_read;
 
-      crypto_params.output_buffer.type = DVR_BUFFER_TYPE_SECURE;
-      crypto_params.output_buffer.addr = (size_t)player->secure_buffer;
-      crypto_params.output_buffer.size = dec_buf_size;
-      ret = player->dec_func(&crypto_params, player->dec_userdata);
-      wbufs.buf_data = player->secure_buffer;
-      wbufs.buf_type = TS_INPUT_BUFFER_TYPE_SECURE;
-      if (ret != DVR_SUCCESS) {
-        DVR_PB_DG(1, "decrypt failed");
+      if (player->is_secure_mode) {
+          crypto_params.output_buffer.type = DVR_BUFFER_TYPE_SECURE;
+          crypto_params.output_buffer.addr = (size_t)player->secure_buffer;
+          crypto_params.output_buffer.size = dec_buf_size;
+          ret = player->dec_func(&crypto_params, player->dec_userdata);
+          input_buffer.buf_data = player->secure_buffer;
+          input_buffer.buf_type = TS_INPUT_BUFFER_TYPE_SECURE;
+          if (ret != DVR_SUCCESS) {
+            DVR_PB_INFO("decrypt failed");
+          }
+          input_buffer.buf_size = crypto_params.output_size;
+      } else {  // only for NAGRA
+          crypto_params.output_buffer.type = crypto_params.input_buffer.type;
+          crypto_params.output_buffer.addr = (size_t)dec_bufs.buf_data;
+          crypto_params.output_buffer.size = crypto_params.input_buffer.size;
+          ret = player->dec_func(&crypto_params, player->dec_userdata);
+          input_buffer.buf_data = (uint8_t*)crypto_params.output_buffer.addr;
+          input_buffer.buf_type = TS_INPUT_BUFFER_TYPE_NORMAL;
+          if (ret != DVR_SUCCESS) {
+            DVR_PB_INFO("decrypt failed");
+          }
+          input_buffer.buf_size = crypto_params.output_buffer.size;
       }
-      wbufs.buf_size = crypto_params.output_size;
     } else if (player->cryptor) {
-      uint32_t len = real_read;
+      int len = real_read;
       am_crypt_des_crypt(player->cryptor, dec_bufs.buf_data, buf, &len, 1);
-      wbufs.buf_data = dec_bufs.buf_data;
-      wbufs.buf_type = TS_INPUT_BUFFER_TYPE_NORMAL;
-      wbufs.buf_size = len;
+      input_buffer.buf_data = dec_bufs.buf_data;
+      input_buffer.buf_type = TS_INPUT_BUFFER_TYPE_NORMAL;
+      input_buffer.buf_size = len;
     }
 rewrite:
     if (player->drop_ts == DVR_TRUE) {
       //need drop ts data when seek occur.we need read next loop,drop this ts data
       goto_rewrite = DVR_FALSE;
       real_read = 0;
+      pthread_mutex_lock(&player->segment_lock);
       player->ts_cache_len = 0;
       player->drop_ts = DVR_FALSE;
-    DVR_PB_DG(1, "----drop ts");
+      pthread_mutex_unlock(&player->segment_lock);
+      DVR_PB_INFO("----drop ts");
       continue;
     }
 
     pthread_mutex_lock(&player->segment_lock);
     player->ts_cache_len = real_read;
-    first_write++;
-    if (first_write == 1)
-    DVR_PB_DG(1, "----firsr write ts data");
-    ret = AmTsPlayer_writeData(player->handle, &wbufs, write_timeout_ms);
-    if (ret == AM_TSPLAYER_OK) {
-    DVR_PB_DG(1, "----ok write ts data");
+    //used for printf first write data time.
+    //to check change channel kpi.
+    if (first_write == 0) {
+      first_write++;
+      DVR_PB_INFO("----first write ts data");
+    }
 
+    ret = AmTsPlayer_writeData(player->handle, &input_buffer, write_timeout_ms);
+    if (ret == AM_TSPLAYER_OK) {
       player->ts_cache_len = 0;
       pthread_mutex_unlock(&player->segment_lock);
       real_read = 0;
       write_success++;
       if (CONTROL_SPEED_ENABLE == 1) {
 check0:
+            if (!player->is_running) {
+                //DVR_PB_DEBUG(1, "playback thread exit");
+                break;
+            }
             if (_dvr_check_speed_con((DVR_PlaybackHandle_t)player) == DVR_FALSE){
-              pthread_mutex_lock(&player->lock);
+              dvr_mutex_lock(&player->lock);
               _dvr_playback_timeoutwait((DVR_PlaybackHandle_t)player, 50);
-              pthread_mutex_unlock(&player->lock);
+              dvr_mutex_unlock(&player->lock);
               _dvr_playback_sent_playtime((DVR_PlaybackHandle_t)player, DVR_FALSE);
               goto check0;
             }
       }
-      //DVR_PB_DG(1, "write  write_success:%d wbufs.buf_size:%d", write_success, wbufs.buf_size);
-      continue;
+      //DVR_PB_INFO("write  write_success:%d input_buffer.buf_size:%d", write_success, input_buffer.buf_size);
     } else {
         pthread_mutex_unlock(&player->segment_lock);
-      DVR_PB_DG(1, "write time out write_success:%d wbufs.buf_size:%d systime:%u",
+      DVR_PB_INFO("write time out write_success:%d input_buffer.buf_size:%d systime:%u",
                     write_success,
-                    wbufs.buf_size,
+                    input_buffer.buf_size,
                     _dvr_time_getClock());
 
       write_success = 0;
       if (CONTROL_SPEED_ENABLE == 1) {
 check1:
+        if (!player->is_running) {
+            //DVR_PB_DEBUG(1, "playback thread exit");
+            break;
+        }
         if (_dvr_check_speed_con((DVR_PlaybackHandle_t)player) == DVR_FALSE){
-          pthread_mutex_lock(&player->lock);
+          dvr_mutex_lock(&player->lock);
           _dvr_playback_timeoutwait((DVR_PlaybackHandle_t)player, 50);
-          pthread_mutex_unlock(&player->lock);
+          dvr_mutex_unlock(&player->lock);
           _dvr_playback_sent_playtime((DVR_PlaybackHandle_t)player, DVR_FALSE);
           goto check1;
         }
       }
-      pthread_mutex_lock(&player->lock);
+      dvr_mutex_lock(&player->lock);
       _dvr_playback_timeoutwait((DVR_PlaybackHandle_t)player, timeout);
-      pthread_mutex_unlock(&player->lock);
+      dvr_mutex_unlock(&player->lock);
       if (!player->is_running) {
-        DVR_PB_DG(1, "playback thread exit");
+        DVR_PB_INFO("playback thread exit");
          break;
       }
       goto_rewrite = DVR_TRUE;
@@ -1455,7 +1571,7 @@
     }
   }
 end:
-  DVR_PB_DG(1, "playback thread is end");
+  DVR_PB_INFO("playback thread is end");
   free(buf);
   free(dec_bufs.buf_data);
   return NULL;
@@ -1467,10 +1583,10 @@
   DVR_Playback_t *player = (DVR_Playback_t *) handle;
 
   if (player == NULL) {
-    DVR_PB_DG(1, "player is NULL");
+    DVR_PB_INFO("player is NULL");
     return DVR_FAILURE;
   }
-  DVR_PB_DG(1, "start thread is_running:[%d]", player->is_running);
+  DVR_PB_INFO("start thread is_running:[%d]", player->is_running);
   if (player->is_running == DVR_TRUE) {
     return 0;
   }
@@ -1487,11 +1603,11 @@
   DVR_Playback_t *player = (DVR_Playback_t *) handle;
 
   if (player == NULL) {
-    DVR_PB_DG(1, "player is NULL");
+    DVR_PB_INFO("player is NULL");
     return DVR_FAILURE;
   }
 
-  DVR_PB_DG(1, "stopthread------[%d]", player->is_running);
+  DVR_PB_INFO("stopthread------[%d]", player->is_running);
   if (player->is_running == DVR_TRUE)
   {
     player->is_running = DVR_FALSE;
@@ -1502,24 +1618,13 @@
     segment_close(player->r_handle);
     player->r_handle = NULL;
   }
-  DVR_PB_DG(1, ":end");
+  DVR_PB_INFO(":end");
   return 0;
 }
 
 static int getFakePid()
 {
-   char fake_pid_prop[] = "vendor.tv.dtv.fake_pid";
-   char buf[32];
-   int pid = 0xffff;
-
-   dvr_prop_read(fake_pid_prop, buf, sizeof(buf));
-
-   if (sscanf(buf, "%i", &pid) != 1)
-   {
-      DVR_PB_DG(1, "get fake pid error");
-      pid = 0xffff;
-   }
-   return pid;
+   return dvr_prop_read_int("vendor.tv.dtv.fake_pid",0xffff);
 }
 
 void dvr_playback_change_seek_state(DVR_PlaybackHandle_t handle,int pid) {
@@ -1527,18 +1632,18 @@
   DVR_ASSERT(handle);
   DVR_Playback_t *player = (DVR_Playback_t *) handle;
   if (player == NULL) {
-    DVR_PB_DG(1, "player is NULL");
+    DVR_PB_INFO("player is NULL");
     return ;
   }
   if (player->need_seek_start == DVR_FALSE) {
-    DVR_PB_DG(1, "player need_seek_start is false");
+    DVR_PB_INFO("player need_seek_start is false");
     return ;
   }
 
   if (pid != player->fake_pid) {
       player->need_seek_start = DVR_FALSE;
   }
-  DVR_PB_DG(1, "player player->need_seek_start=%d", player->need_seek_start);
+  DVR_PB_INFO("player player->need_seek_start=%d", player->need_seek_start);
 }
 
 /**\brief Open an dvr palyback
@@ -1553,8 +1658,9 @@
   pthread_condattr_t  cattr;
 
   player = (DVR_Playback_t*)calloc(1, sizeof(DVR_Playback_t));
+  DVR_RETURN_IF_FALSE(player);
 
-  pthread_mutex_init(&player->lock, NULL);
+  dvr_mutex_init(&player->lock);
   pthread_mutex_init(&player->segment_lock, NULL);
   pthread_condattr_init(&cattr);
   pthread_condattr_setclock(&cattr, CLOCK_MONOTONIC);
@@ -1567,7 +1673,7 @@
   player->cmd.cur_cmd = DVR_PLAYBACK_CMD_STOP;
   player->cmd.speed.speed.speed = PLAYBACK_SPEED_X1;
   player->cmd.state = DVR_PLAYBACK_STATE_STOP;
-  player->state = DVR_PLAYBACK_STATE_STOP;
+  DVR_PLAYER_CHANGE_STATE(player,DVR_PLAYBACK_STATE_STOP);
   player->cmd.pos = 0;
   player->speed = 1.0f;
   player->first_trans_ok = DVR_FALSE;
@@ -1575,7 +1681,7 @@
   //store open params
   player->openParams.dmx_dev_id = params->dmx_dev_id;
   player->openParams.block_size = params->block_size;
-  DVR_PB_DG(1, "playback open block_size:[%d]",params->block_size);
+  DVR_PB_INFO("playback open block_size:[%d]",params->block_size);
   player->openParams.is_timeshift = params->is_timeshift;
   player->openParams.event_fn = params->event_fn;
   player->openParams.event_userdata = params->event_userdata;
@@ -1591,7 +1697,7 @@
   if (0 && player->player_callback_func == NULL) {
     AmTsPlayer_registerCb(player->handle, _dvr_tsplayer_callback_test, player);
     AmTsPlayer_getCb(player->handle, &player->player_callback_func, &player->player_callback_userdata);
-    DVR_PB_DG(1, "playback open get callback[%p][%p][%p][%p]",
+    DVR_PB_INFO("playback open get callback[%p][%p][%p][%p]",
                   player->player_callback_func,
                   player->player_callback_userdata,
                   _dvr_tsplayer_callback_test,
@@ -1605,6 +1711,7 @@
   player->cur_segment_id = UINT64_MAX;
   player->last_segment_id = 0LL;
   player->segment_is_open = DVR_FALSE;
+  player->audio_presentation_id = -1;
 
   //init ff fb time
   player->fffb_current = 0;
@@ -1617,10 +1724,10 @@
   //allocate cryptor if have clearkey
   if (params->keylen > 0) {
     player->cryptor = am_crypt_des_open((uint8_t *)params->clearkey,
-				(uint8_t *)params->cleariv,
-				params->keylen * 8);
+                (uint8_t *)params->cleariv,
+                params->keylen * 8);
     if (!player->cryptor) {
-      DVR_DEBUG(1, "%s , open des cryptor failed!!!\n", __func__);
+      DVR_INFO("%s , open des cryptor failed!!!\n", __func__);
     }
   } else {
     player->cryptor = NULL;
@@ -1653,6 +1760,8 @@
   player->limit = 0;
   //need seek to start pos
   player->first_start_time = 0;
+  player->first_start_id = UINT64_MAX;
+  player->check_cache_flag = DVR_TRUE;
   player->need_seek_start = DVR_TRUE;
   //fake_pid init
   player->fake_pid = getFakePid();
@@ -1668,38 +1777,38 @@
 int dvr_playback_close(DVR_PlaybackHandle_t handle) {
 
   DVR_ASSERT(handle);
-  DVR_PB_DG(1, ":into");
+  DVR_PB_INFO(":into");
   DVR_Playback_t *player = (DVR_Playback_t *) handle;
   if (player == NULL) {
-    DVR_PB_DG(1, "player is NULL");
+    DVR_PB_INFO("player is NULL");
     return DVR_FAILURE;
   }
 
   if (player->state != DVR_PLAYBACK_STATE_STOP)
   {
-    DVR_PB_DG(1, "player->state %s", _dvr_playback_state_toString(player->state));
+    DVR_PB_INFO("player->state %s", _dvr_playback_state_toString(player->state));
     if (player->cryptor) {
       am_crypt_des_close(player->cryptor);
       player->cryptor = NULL;
     }
     dvr_playback_stop(handle, DVR_TRUE);
-    DVR_PB_DG(1, "player->state %s", _dvr_playback_state_toString(player->state));
+    DVR_PB_INFO("player->state %s", _dvr_playback_state_toString(player->state));
   } else {
-    DVR_PB_DG(1, ":is stoped state");
+    DVR_PB_INFO(":is stoped state");
   }
-  DVR_PB_DG(1, ":into");
-  pthread_mutex_destroy(&player->lock);
+  DVR_PB_INFO(":into");
+  dvr_mutex_destroy(&player->lock);
+  pthread_mutex_destroy(&player->segment_lock);
   pthread_cond_destroy(&player->cond);
 
   if (player) {
     free(player);
-    player = NULL;
   }
-  DVR_PB_DG(1, ":end");
+  DVR_PB_INFO(":end");
   return DVR_SUCCESS;
 }
 
-/**\brief Start play audio and video, used start auido api and start video api
+/**\brief Start play audio and video, used start audio api and start video api
  * \param[in] handle playback handle
  * \param[in] params audio playback params,contains fmt and pid...
  * \retval DVR_SUCCESS On success
@@ -1707,19 +1816,19 @@
  */
 int dvr_playback_start(DVR_PlaybackHandle_t handle, DVR_PlaybackFlag_t flag) {
   DVR_Playback_t *player = (DVR_Playback_t *) handle;
-  am_tsplayer_video_params    vparams;
-  am_tsplayer_audio_params    aparams;
-  am_tsplayer_audio_params    adparams;
+  am_tsplayer_video_params    video_params;
+  am_tsplayer_audio_params    audio_params;
+  am_tsplayer_audio_params    ad_params;
 
-  memset(&vparams, 0, sizeof(vparams));
-  memset(&aparams, 0, sizeof(aparams));
+  memset(&video_params, 0, sizeof(video_params));
+  memset(&audio_params, 0, sizeof(audio_params));
 
   if (player == NULL) {
-    DVR_PB_DG(1, "player is NULL");
+    DVR_PB_INFO("player is NULL");
     return DVR_FAILURE;
   }
   uint64_t segment_id = player->cur_segment_id;
-  DVR_PB_DG(1, "[%p]segment_id:[%lld]", handle, segment_id);
+  DVR_PB_INFO("[%p]segment_id:[%lld]", handle, segment_id);
 
   player->first_frame = 0;
   //can used start api to resume playback
@@ -1727,27 +1836,27 @@
     return dvr_playback_resume(handle);
   }
   if (player->cmd.state == DVR_PLAYBACK_STATE_START) {
-    //if flag is puased and not decodec first frame. if user resume, we need
+    //if flag is paused and not decode first frame. if user resume, we need
     //clear flag and set trickmode none
     if ((player->play_flag&DVR_PLAYBACK_STARTED_PAUSEDLIVE) == DVR_PLAYBACK_STARTED_PAUSEDLIVE) {
-      DVR_PB_DG(1, "[%p]clear pause live flag and clear trick mode", handle);
+      DVR_PB_INFO("[%p]clear pause live flag and clear trick mode", handle);
       player->play_flag = player->play_flag & (~DVR_PLAYBACK_STARTED_PAUSEDLIVE);
       AmTsPlayer_setTrickMode(player->handle, AV_VIDEO_TRICK_MODE_NONE);
     }
-    DVR_PB_DG(1, "stat is start, not need into start play");
+    DVR_PB_INFO("stat is start, not need into start play");
     return DVR_SUCCESS;
   }
   player->play_flag = flag;
   player->first_trans_ok = DVR_FALSE;
   //get segment info and audio video pid fmt ;
-  DVR_PB_DG(1, "lock flag:0x%x", flag);
-  pthread_mutex_lock(&player->lock);
-  _dvr_playback_get_playinfo(handle, segment_id, &vparams, &aparams, &adparams);
+  DVR_PB_INFO("lock flag:0x%x", flag);
+  dvr_mutex_lock(&player->lock);
+  _dvr_playback_get_playinfo(handle, segment_id, &video_params, &audio_params, &ad_params);
   //start audio and video
-  if (vparams.pid != player->fake_pid && !VALID_PID(vparams.pid) && !VALID_PID(aparams.pid)) {
-    //audio abnd video pis is all invalid, return error.
-    DVR_PB_DG(0, "unlock dvr play back start error, not found audio and video info [0x%x]", vparams.pid);
-    pthread_mutex_unlock(&player->lock);
+  if (video_params.pid != player->fake_pid && !VALID_PID(video_params.pid) && !VALID_PID(audio_params.pid)) {
+    //audio and video pids are all invalid, return error.
+    DVR_PB_ERROR("unlock dvr play back start error, not found audio and video info [0x%x]", video_params.pid);
+    dvr_mutex_unlock(&player->lock);
     DVR_Play_Notify_t notify;
     memset(&notify, 0 , sizeof(DVR_Play_Notify_t));
     notify.event = DVR_PLAYBACK_EVENT_TRANSITION_FAILED;
@@ -1759,61 +1868,70 @@
   }
 
   {
-    if (VALID_PID(vparams.pid)) {
+    if (VALID_PID(video_params.pid)) {
       player->has_video = DVR_TRUE;
       //if set flag is pause live, we need set trick mode
       if ((player->play_flag&DVR_PLAYBACK_STARTED_PAUSEDLIVE) == DVR_PLAYBACK_STARTED_PAUSEDLIVE) {
-        DVR_PB_DG(1, "set trick mode -pauselive flag--");
+        DVR_PB_INFO("set trick mode -pauselive flag--");
         AmTsPlayer_setTrickMode(player->handle, AV_VIDEO_TRICK_MODE_PAUSE_NEXT);
       } else if (player->cmd.cur_cmd == DVR_PLAYBACK_CMD_FB
         || player->cmd.cur_cmd == DVR_PLAYBACK_CMD_FF) {
-        DVR_PB_DG(1, "set trick mode -fffb--at pause live");
+        DVR_PB_INFO("set trick mode -fffb--at pause live");
         AmTsPlayer_setTrickMode(player->handle, AV_VIDEO_TRICK_MODE_PAUSE_NEXT);
       } else {
-        DVR_PB_DG(1, "set trick mode ---none");
+        DVR_PB_INFO("set trick mode ---none");
         AmTsPlayer_setTrickMode(player->handle, AV_VIDEO_TRICK_MODE_NONE);
       }
       AmTsPlayer_showVideo(player->handle);
-      AmTsPlayer_setVideoParams(player->handle,  &vparams);
+      AmTsPlayer_setVideoParams(player->handle,  &video_params);
       AmTsPlayer_setVideoBlackOut(player->handle, 1);
       AmTsPlayer_startVideoDecoding(player->handle);
     }
 
-    DVR_PB_DG(1, "player->cmd.cur_cmd:%d vpid[0x%x]apis[0x%x]", player->cmd.cur_cmd, vparams.pid, aparams.pid);
+    DVR_PB_INFO("player->cmd.cur_cmd:%d vpid[0x%x]apis[0x%x]", player->cmd.cur_cmd, video_params.pid, audio_params.pid);
     player->last_send_time_id = UINT64_MAX;
     if (player->cmd.cur_cmd == DVR_PLAYBACK_CMD_FB
       || player->cmd.cur_cmd == DVR_PLAYBACK_CMD_FF) {
       player->cmd.state = DVR_PLAYBACK_STATE_START;
-      player->state = DVR_PLAYBACK_STATE_START;
+      DVR_PLAYER_CHANGE_STATE(player,DVR_PLAYBACK_STATE_START);
     } else {
       player->cmd.last_cmd = player->cmd.cur_cmd;
       player->cmd.cur_cmd = DVR_PLAYBACK_CMD_START;
       if (IS_FAST_SPEED(player->cmd.speed.speed.speed)) {
         //set fast play
-        DVR_PB_DG(1, "start fast");
+        DVR_PB_INFO("start fast");
         AmTsPlayer_startFast(player->handle, (float)player->cmd.speed.speed.speed/100.0f);
       } else {
-        if (VALID_PID(adparams.pid)) {
+        if (VALID_PID(ad_params.pid)) {
           player->has_ad_audio = DVR_TRUE;
-          DVR_PB_DG(1, "start ad audio");
-          dvr_playback_change_seek_state(handle, adparams.pid);
-          AmTsPlayer_setADParams(player->handle,  &adparams);
+          DVR_PB_INFO("start ad audio");
+          dvr_playback_change_seek_state(handle, ad_params.pid);
+          AmTsPlayer_setADParams(player->handle,  &ad_params);
           AmTsPlayer_enableADMix(player->handle);
         }
-        if (VALID_PID(aparams.pid)) {
-          DVR_PB_DG(1, "start audio");
+        if (VALID_PID(audio_params.pid)) {
+          DVR_PB_INFO("start audio");
           player->has_audio = DVR_TRUE;
-          dvr_playback_change_seek_state(handle, aparams.pid);
-          AmTsPlayer_setAudioParams(player->handle,  &aparams);
+          dvr_playback_change_seek_state(handle, audio_params.pid);
+          AmTsPlayer_setAudioParams(player->handle,  &audio_params);
+          if (player->audio_presentation_id > -1) {
+            AmTsPlayer_setParams(player->handle, AM_TSPLAYER_KEY_AUDIO_PRESENTATION_ID, &player->audio_presentation_id);
+          }
           AmTsPlayer_startAudioDecoding(player->handle);
         }
       }
       player->cmd.state = DVR_PLAYBACK_STATE_START;
-      player->state = DVR_PLAYBACK_STATE_START;
+      DVR_PLAYER_CHANGE_STATE(player,DVR_PLAYBACK_STATE_START);
     }
   }
-  DVR_PB_DG(1, "unlock");
-  pthread_mutex_unlock(&player->lock);
+#ifdef AVSYNC_USED_PCR
+  if (player && VALID_PID(player->cur_segment.pids.pcr.pid)) {
+    DVR_PB_INFO("start set pcr [%d]", player->cur_segment.pids.pcr.pid);
+    AmTsPlayer_setPcrPid(player->handle, player->cur_segment.pids.pcr.pid);
+  }
+#endif
+  DVR_PB_DEBUG("unlock");
+  dvr_mutex_unlock(&player->lock);
   _start_playback_thread(handle);
   return DVR_SUCCESS;
 }
@@ -1825,24 +1943,21 @@
  */
 int dvr_playback_add_segment(DVR_PlaybackHandle_t handle, DVR_PlaybackSegmentInfo_t *info) {
   DVR_Playback_t *player = (DVR_Playback_t *) handle;
+  DVR_RETURN_IF_FALSE(player);
 
-  if (player == NULL) {
-    DVR_PB_DG(1, "player is NULL");
-    return DVR_FAILURE;
-  }
-
-  DVR_PB_DG(1, "add segment id: %lld %p", info->segment_id, handle);
+  DVR_PB_INFO("add segment id: %lld %p", info->segment_id, handle);
   DVR_PlaybackSegmentInfo_t *segment;
 
   segment = malloc(sizeof(DVR_PlaybackSegmentInfo_t));
+  DVR_RETURN_IF_FALSE(segment);
   memset(segment, 0, sizeof(DVR_PlaybackSegmentInfo_t));
 
-  //not memcpy chun info.
+  //not memcpy chunk info.
   segment->segment_id = info->segment_id;
   //cp location
   memcpy(segment->location, info->location, DVR_MAX_LOCATION_SIZE);
 
-  DVR_PB_DG(1, "add location [%s]id[%lld]flag[%x]", segment->location, segment->segment_id, info->flags);
+  DVR_PB_INFO("add location [%s]id[%lld]flag[%x]", segment->location, segment->segment_id, info->flags);
   segment->flags = info->flags;
 
   //pids
@@ -1860,11 +1975,11 @@
 
   segment->pids.pcr.pid = info->pids.pcr.pid;
 
-  DVR_PB_DG(1, "lock pid [0x%x][0x%x][0x%x][0x%x]", segment->pids.video.pid,segment->pids.audio.pid, info->pids.video.pid,info->pids.audio.pid);
-  pthread_mutex_lock(&player->lock);
-  list_add_tail(&segment->head, &player->segment_list);
-  pthread_mutex_unlock(&player->lock);
-  DVR_PB_DG(1, "unlock");
+  DVR_PB_INFO("lock pid [0x%x][0x%x][0x%x][0x%x]", segment->pids.video.pid,segment->pids.audio.pid, info->pids.video.pid,info->pids.audio.pid);
+  dvr_mutex_lock(&player->lock);
+  list_add_tail(segment, &player->segment_list);
+  dvr_mutex_unlock(&player->lock);
+  DVR_PB_DEBUG("unlock");
 
   return DVR_SUCCESS;
 }
@@ -1876,18 +1991,18 @@
  */
 int dvr_playback_remove_segment(DVR_PlaybackHandle_t handle, uint64_t segment_id) {
   DVR_Playback_t *player = (DVR_Playback_t *) handle;
-  DVR_PB_DG(1, "remove segment id: %lld", segment_id);
+  DVR_PB_INFO("remove segment id: %lld", segment_id);
   if (player == NULL) {
-    DVR_PB_DG(1, "player is NULL");
+    DVR_PB_INFO("player is NULL");
     return DVR_FAILURE;
   }
 
   if (segment_id == player->cur_segment_id) {
-    DVR_PB_DG(1, "not suport remove curren segment id: %lld", segment_id);
+    DVR_PB_INFO("not support remove current segment id: %lld", segment_id);
     return DVR_FAILURE;
   }
-  DVR_PB_DG(1, "lock");
-  pthread_mutex_lock(&player->lock);
+  DVR_PB_DEBUG("lock");
+  dvr_mutex_lock(&player->lock);
   DVR_PlaybackSegmentInfo_t *segment = NULL;
   DVR_PlaybackSegmentInfo_t *segment_tmp = NULL;
   list_for_each_entry_safe(segment, segment_tmp, &player->segment_list, head)
@@ -1898,8 +2013,8 @@
       break;
     }
   }
-  DVR_PB_DG(1, "unlock");
-  pthread_mutex_unlock(&player->lock);
+  DVR_PB_DEBUG("unlock");
+  dvr_mutex_unlock(&player->lock);
 
   return DVR_SUCCESS;
 }
@@ -1912,19 +2027,23 @@
 int dvr_playback_update_segment_flags(DVR_PlaybackHandle_t handle,
   uint64_t segment_id, DVR_PlaybackSegmentFlag_t flags) {
   DVR_Playback_t *player = (DVR_Playback_t *) handle;
-  DVR_PB_DG(1, "update segment id: %lld flag:%d", segment_id, flags);
+  DVR_PB_INFO("update segment id: %lld flag:%d", segment_id, flags);
   if (player == NULL) {
-    DVR_PB_DG(1, "player is NULL");
+    DVR_PB_INFO("player is NULL");
     return DVR_FAILURE;
   }
   if (player->vendor == DVR_PLAYBACK_VENDOR_AML) {
-    DVR_PB_DG(1, "vendor is amlogic. not  hide or show av and update segment");
+    DVR_PB_INFO("vendor is amlogic. not  hide or show av and update segment");
     return DVR_SUCCESS;
   }
 
   DVR_PlaybackSegmentInfo_t *segment;
-  DVR_PB_DG(1, "lock");
-  pthread_mutex_lock(&player->lock);
+  DVR_PB_DEBUG("lock");
+  dvr_mutex_lock(&player->lock);
+  // This error is suppressed as the macro code is picked from kernel.
+  // prefetch() here incurring self_assign is used to avoid some compiling
+  // warnings.
+  // coverity[self_assign]
   list_for_each_entry(segment, &player->segment_list, head)
   {
     if (segment->segment_id != segment_id) {
@@ -1937,13 +2056,13 @@
       if ((segment->flags & DVR_PLAYBACK_SEGMENT_DISPLAYABLE) == DVR_PLAYBACK_SEGMENT_DISPLAYABLE
         && (flags & DVR_PLAYBACK_SEGMENT_DISPLAYABLE) == 0) {
         //disable display, mute
-        DVR_PB_DG(1, "mute av");
+        DVR_PB_INFO("mute av");
         AmTsPlayer_hideVideo(player->handle);
         AmTsPlayer_setAudioMute(player->handle, 1, 1);
       } else if ((segment->flags & DVR_PLAYBACK_SEGMENT_DISPLAYABLE) == 0 &&
           (flags & DVR_PLAYBACK_SEGMENT_DISPLAYABLE) == DVR_PLAYBACK_SEGMENT_DISPLAYABLE) {
         //enable display, unmute
-        DVR_PB_DG(1, "unmute av");
+        DVR_PB_INFO("unmute av");
         AmTsPlayer_showVideo(player->handle);
         AmTsPlayer_setAudioMute(player->handle, 0, 0);
       } else {
@@ -1955,8 +2074,8 @@
     //continue , only set flag
     segment->flags = flags;
   }
-  DVR_PB_DG(1, "unlock");
-  pthread_mutex_unlock(&player->lock);
+  DVR_PB_DEBUG("unlock");
+  dvr_mutex_unlock(&player->lock);
   return DVR_SUCCESS;
 }
 
@@ -1981,10 +2100,10 @@
   }
 
   if (player == NULL) {
-    DVR_PB_DG(1, "player is NULL");
+    DVR_PB_INFO("player is NULL");
     return DVR_FAILURE;
   }
-  DVR_PB_DG(1, " do check");
+  DVR_PB_INFO(" do check");
   if (now_pid.pid == set_pid.pid) {
     //do nothing
     return 0;
@@ -1992,22 +2111,22 @@
     if (VALID_PID(now_pid.pid)) {
       //stop now stream
       if (type == 0) {
-        //stop vieo
+        //stop video
         if (player->has_video == DVR_TRUE) {
-          DVR_PB_DG(1, "stop video");
+          DVR_PB_INFO("stop video");
           AmTsPlayer_stopVideoDecoding(player->handle);
           player->has_video = DVR_FALSE;
         }
       } else if (type == 1) {
         //stop audio
         if (player->has_audio == DVR_TRUE) {
-          DVR_PB_DG(1, "stop audio");
+          DVR_PB_INFO("stop audio");
           AmTsPlayer_stopAudioDecoding(player->handle);
           player->has_audio = DVR_FALSE;
         }
       } else if (type == 2) {
         //stop sub audio
-        DVR_PB_DG(1, "stop ad");
+        DVR_PB_INFO("stop ad");
         AmTsPlayer_disableADMix(player->handle);
       } else if (type == 3) {
         //pcr
@@ -2016,77 +2135,106 @@
     if (VALID_PID(set_pid.pid)) {
       //start
       if (type == 0) {
-        //start vieo
-        am_tsplayer_video_params vparams;
-        vparams.pid = set_pid.pid;
-        vparams.codectype = _dvr_convert_stream_fmt(set_pid.format, DVR_FALSE);
+        //start video
+        am_tsplayer_video_params video_params;
+        video_params.pid = set_pid.pid;
+        video_params.codectype = _dvr_convert_stream_fmt(set_pid.format, DVR_FALSE);
         player->has_video = DVR_TRUE;
-        DVR_PB_DG(1, "start video pid[%d]fmt[%d]",vparams.pid, vparams.codectype);
-        AmTsPlayer_setVideoParams(player->handle,  &vparams);
+        DVR_PB_INFO("start video pid[%d]fmt[%d]",video_params.pid, video_params.codectype);
+        AmTsPlayer_setVideoParams(player->handle,  &video_params);
         AmTsPlayer_startVideoDecoding(player->handle);
-        //playback_device_video_start(player->handle,&vparams);
+        //playback_device_video_start(player->handle,&video_params);
       } else if (type == 1) {
         //start audio
         if (player->cmd.speed.speed.speed == PLAYBACK_SPEED_X1) {
           if (VALID_PID(set_pids.ad.pid)) {
-            am_tsplayer_audio_params adparams;
-            adparams.pid = set_pids.ad.pid;
-            adparams.codectype= _dvr_convert_stream_fmt(set_pids.ad.format, DVR_TRUE);
-            DVR_PB_DG(1, "start ad audio pid[%d]fmt[%d]",adparams.pid, adparams.codectype);
-            AmTsPlayer_setADParams(player->handle,  &adparams);
+            am_tsplayer_audio_params ad_params;
+            ad_params.pid = set_pids.ad.pid;
+            ad_params.codectype= _dvr_convert_stream_fmt(set_pids.ad.format, DVR_TRUE);
+            DVR_PB_INFO("start ad audio pid[%d]fmt[%d]",ad_params.pid, ad_params.codectype);
+            AmTsPlayer_setADParams(player->handle,  &ad_params);
             AmTsPlayer_enableADMix(player->handle);
           }
 
-          am_tsplayer_audio_params aparams;
+          am_tsplayer_audio_params audio_params;
 
-          memset(&aparams, 0, sizeof(aparams));
+          memset(&audio_params, 0, sizeof(audio_params));
 
-          aparams.pid = set_pid.pid;
-          aparams.codectype= _dvr_convert_stream_fmt(set_pid.format, DVR_TRUE);
+          audio_params.pid = set_pid.pid;
+          audio_params.codectype= _dvr_convert_stream_fmt(set_pid.format, DVR_TRUE);
           player->has_audio = DVR_TRUE;
-          DVR_PB_DG(1, "start audio pid[%d]fmt[%d]",aparams.pid, aparams.codectype);
-          AmTsPlayer_setAudioParams(player->handle,  &aparams);
+          DVR_PB_INFO("start audio pid[%d]fmt[%d]",audio_params.pid, audio_params.codectype);
+          AmTsPlayer_setAudioParams(player->handle,  &audio_params);
+          if (player->audio_presentation_id > -1) {
+            AmTsPlayer_setParams(player->handle, AM_TSPLAYER_KEY_AUDIO_PRESENTATION_ID, &player->audio_presentation_id);
+          }
           AmTsPlayer_startAudioDecoding(player->handle);
-          //playback_device_audio_start(player->handle,&aparams);
+          //playback_device_audio_start(player->handle,&audio_params);
         }
       } else if (type == 2) {
         if (player->cmd.speed.speed.speed == PLAYBACK_SPEED_X1) {
           if (set_pids.audio.pid == now_pids.audio.pid) {
             //stop audio if audio pid not change
-            DVR_PB_DG(1, "stop audio when start ad");
+            DVR_PB_INFO("stop audio when start ad");
             AmTsPlayer_stopAudioDecoding(player->handle);
           }
-          am_tsplayer_audio_params aparams;
+          am_tsplayer_audio_params audio_params;
 
-          memset(&aparams, 0, sizeof(aparams));
-          aparams.pid = set_pid.pid;
-          aparams.codectype= _dvr_convert_stream_fmt(set_pid.format, DVR_TRUE);
+          memset(&audio_params, 0, sizeof(audio_params));
+          audio_params.pid = set_pid.pid;
+          audio_params.codectype= _dvr_convert_stream_fmt(set_pid.format, DVR_TRUE);
           player->has_audio = DVR_TRUE;
-          DVR_PB_DG(1, "start ad audio pid[%d]fmt[%d]",aparams.pid, aparams.codectype);
-          AmTsPlayer_setADParams(player->handle,  &aparams);
+          DVR_PB_INFO("start ad audio pid[%d]fmt[%d]",audio_params.pid, audio_params.codectype);
+          AmTsPlayer_setADParams(player->handle,  &audio_params);
           AmTsPlayer_enableADMix(player->handle);
 
           if (set_pids.audio.pid == now_pids.audio.pid) {
-              am_tsplayer_audio_params aparams;
+              am_tsplayer_audio_params audio_params;
 
-              memset(&aparams, 0, sizeof(aparams));
+              memset(&audio_params, 0, sizeof(audio_params));
 
-              aparams.pid = set_pids.audio.pid;
-              aparams.codectype= _dvr_convert_stream_fmt(set_pids.audio.format, DVR_TRUE);
+              audio_params.pid = set_pids.audio.pid;
+              audio_params.codectype= _dvr_convert_stream_fmt(set_pids.audio.format, DVR_TRUE);
               player->has_audio = DVR_TRUE;
-              DVR_PB_DG(1, "restart audio when start ad");
-              AmTsPlayer_setAudioParams(player->handle,  &aparams);
+              DVR_PB_INFO("restart audio when start ad");
+              AmTsPlayer_setAudioParams(player->handle,  &audio_params);
+              if (player->audio_presentation_id > -1) {
+                AmTsPlayer_setParams(player->handle, AM_TSPLAYER_KEY_AUDIO_PRESENTATION_ID, &player->audio_presentation_id);
+              }
               AmTsPlayer_startAudioDecoding(player->handle);
           }
         }
       } else if (type == 3) {
         //pcr
-        DVR_PB_DG(1, "start set pcr [%d]", set_pid.pid);
+        DVR_PB_INFO("start set pcr [%d]", set_pid.pid);
         AmTsPlayer_setPcrPid(player->handle, set_pid.pid);
       }
       //audio and video all close
       if (!player->has_audio && !player->has_video) {
-        player->state = DVR_PLAYBACK_STATE_STOP;
+        DVR_PLAYER_CHANGE_STATE(player,DVR_PLAYBACK_STATE_STOP);
+      }
+    } else if (type == 2) {
+      //case disable ad
+        DVR_PB_INFO("restart  audio when stop ad");
+      if (player->cmd.speed.speed.speed == PLAYBACK_SPEED_X1) {
+        if (VALID_PID(now_pids.audio.pid)) {
+          //stop audio if audio pid not change
+          DVR_PB_INFO("stop audio when stop ad pid [0x%x]", now_pids.audio.pid);
+          AmTsPlayer_stopAudioDecoding(player->handle);
+          am_tsplayer_audio_params audio_params;
+
+          memset(&audio_params, 0, sizeof(audio_params));
+
+          audio_params.pid = now_pids.audio.pid;
+          audio_params.codectype= _dvr_convert_stream_fmt(now_pids.audio.format, DVR_TRUE);
+          player->has_audio = DVR_TRUE;
+          DVR_PB_INFO("restart audio when stop ad");
+          AmTsPlayer_setAudioParams(player->handle,  &audio_params);
+          if (player->audio_presentation_id > -1) {
+            AmTsPlayer_setParams(player->handle, AM_TSPLAYER_KEY_AUDIO_PRESENTATION_ID, &player->audio_presentation_id);
+          }
+          AmTsPlayer_startAudioDecoding(player->handle);
+        }
       }
     }
   }
@@ -2103,36 +2251,40 @@
 int dvr_playback_only_update_segment_pids(DVR_PlaybackHandle_t handle, uint64_t segment_id, DVR_PlaybackPids_t *p_pids) {
   DVR_Playback_t *player = (DVR_Playback_t *) handle;
   if (player == NULL) {
-    DVR_PB_DG(1, "player is NULL");
+    DVR_PB_INFO("player is NULL");
     return DVR_FAILURE;
   }
 
   DVR_PlaybackSegmentInfo_t *segment;
-  DVR_PB_DG(1, "lock");
-  pthread_mutex_lock(&player->lock);
-  DVR_PB_DG(1, "get lock update segment id: %lld cur id %lld", segment_id, player->cur_segment_id);
+  DVR_PB_DEBUG("lock");
+  dvr_mutex_lock(&player->lock);
+  DVR_PB_INFO("get lock update segment id: %lld cur id %lld", segment_id, player->cur_segment_id);
+  // This error is suppressed as the macro code is picked from kernel.
+  // prefetch() here incurring self_assign is used to avoid some compiling
+  // warnings.
+  // coverity[self_assign]
   list_for_each_entry(segment, &player->segment_list, head)
   {
     if (segment->segment_id == segment_id) {
       if (player->cur_segment_id == segment_id) {
         if (player->cmd.state == DVR_PLAYBACK_STATE_FF
-          || player->cmd.state == DVR_PLAYBACK_STATE_FF) {
+          || player->cmd.state == DVR_PLAYBACK_STATE_FB) {
           //do nothing when ff fb
-          DVR_PB_DG(1, "unlock now is ff fb, not to update cur segment info\r\n");
-          pthread_mutex_unlock(&player->lock);
+          DVR_PB_INFO("unlock now is ff fb, not to update cur segment info\r\n");
+          dvr_mutex_unlock(&player->lock);
           return 0;
         }
         memcpy(&player->cur_segment.pids, p_pids, sizeof(DVR_PlaybackPids_t));
       }
       //save pids info
-      DVR_PB_DG(1, ":apid :%d %d", segment->pids.audio.pid, p_pids->audio.pid);
+      DVR_PB_INFO(":apid :%d %d", segment->pids.audio.pid, p_pids->audio.pid);
       memcpy(&segment->pids, p_pids, sizeof(DVR_PlaybackPids_t));
-      DVR_PB_DG(1, ":cp apid :%d %d", segment->pids.audio.pid, p_pids->audio.pid);
+      DVR_PB_INFO(":cp apid :%d %d", segment->pids.audio.pid, p_pids->audio.pid);
       break;
     }
   }
-  DVR_PB_DG(1, "unlock");
-  pthread_mutex_unlock(&player->lock);
+  DVR_PB_DEBUG("unlock");
+  dvr_mutex_unlock(&player->lock);
   return DVR_SUCCESS;
 }
 
@@ -2147,36 +2299,40 @@
 int dvr_playback_update_segment_pids(DVR_PlaybackHandle_t handle, uint64_t segment_id, DVR_PlaybackPids_t *p_pids) {
   DVR_Playback_t *player = (DVR_Playback_t *) handle;
   if (player == NULL) {
-    DVR_PB_DG(1, "player is NULL");
+    DVR_PB_INFO("player is NULL");
     return DVR_FAILURE;
   }
 
   DVR_PlaybackSegmentInfo_t *segment;
-  DVR_PB_DG(1, "lock");
-  pthread_mutex_lock(&player->lock);
-  DVR_PB_DG(1, "get lock update segment id: %lld cur id %lld", segment_id, player->cur_segment_id);
+  DVR_PB_DEBUG("lock");
+  dvr_mutex_lock(&player->lock);
+  DVR_PB_INFO("get lock update segment id: %lld cur id %lld", segment_id, player->cur_segment_id);
 
+  // This error is suppressed as the macro code is picked from kernel.
+  // prefetch() here incurring self_assign is used to avoid some compiling
+  // warnings.
+  // coverity[self_assign]
   list_for_each_entry(segment, &player->segment_list, head)
   {
     if (segment->segment_id == segment_id) {
 
       if (player->cur_segment_id == segment_id) {
         if (player->cmd.state == DVR_PLAYBACK_STATE_FF
-          || player->cmd.state == DVR_PLAYBACK_STATE_FF) {
+          || player->cmd.state == DVR_PLAYBACK_STATE_FB) {
           //do nothing when ff fb
-          DVR_PB_DG(1, "unlock now is ff fb, not to update cur segment info\r\n");
-          pthread_mutex_unlock(&player->lock);
+          DVR_PB_INFO("unlock now is ff fb, not to update cur segment info\r\n");
+          dvr_mutex_unlock(&player->lock);
           return 0;
         }
 
         //if segment is on going segment,we need stop start stream
         if (player->cmd.state == DVR_PLAYBACK_STATE_START) {
-          DVR_PB_DG(1, "unlock ---\r\n");
-          pthread_mutex_unlock(&player->lock);
+          DVR_PB_DEBUG("unlock ---\r\n");
+          dvr_mutex_unlock(&player->lock);
           if (segment->pids.audio.pid != p_pids->audio.pid &&
              segment->pids.audio.pid == 0x1fff) {
                //not used this to seek to start pos.we will
-               //add uopdate only api. if need seek to start
+               //add update only api. if need seek to start
                //pos, we will call only update api and used seek api
                //to start and stop av codec
             if (0 && player->need_seek_start == DVR_TRUE) {
@@ -2187,7 +2343,7 @@
                 if (player->first_start_time > 0)
                   player->first_start_time = player->first_start_time - 1;
                 segment_seek(player->r_handle, (uint64_t)(player->first_start_time), player->openParams.block_size);
-                DVR_PB_DG(0, "unlock segment update need seek time_offset %llu [0x%x][0x%x]", player->first_start_time, segment->pids.audio.pid, segment->pids.ad.pid);
+                DVR_PB_ERROR("unlock segment update need seek time_offset %llu [0x%x][0x%x]", player->first_start_time, segment->pids.audio.pid, segment->pids.ad.pid);
                 pthread_mutex_unlock(&player->segment_lock);
             }
           }
@@ -2200,7 +2356,7 @@
           //check pcr pids stop or restart
           _do_check_pid_info((DVR_PlaybackHandle_t)player, segment->pids, *p_pids, 3);
 
-          pthread_mutex_lock(&player->lock);
+          dvr_mutex_lock(&player->lock);
         } else if (player->cmd.state == DVR_PLAYBACK_STATE_PAUSE) {
           //if state is pause, we need process at resume api. we only record change info
             int v_cmd = DVR_PLAYBACK_CMD_NONE;
@@ -2209,37 +2365,37 @@
               && VALID_PID(p_pids->video.pid)
               && segment->pids.video.pid != p_pids->video.pid) {
               //restart video
-              v_cmd = DVR_PLAYBACK_CMD_VRESTART;
+              v_cmd = DVR_PLAYBACK_CMD_V_RESTART;
             }
             if (!VALID_PID(segment->pids.video.pid)
                 && VALID_PID(p_pids->video.pid)
                 && segment->pids.video.pid != p_pids->video.pid) {
                 //start video
-                v_cmd = DVR_PLAYBACK_CMD_VSTART;
+                v_cmd = DVR_PLAYBACK_CMD_V_START;
             }
             if (VALID_PID(segment->pids.video.pid)
                 && !VALID_PID(p_pids->video.pid)
                 && segment->pids.video.pid != p_pids->video.pid) {
                 //stop video
-                v_cmd = DVR_PLAYBACK_CMD_VSTOP;
+                v_cmd = DVR_PLAYBACK_CMD_V_STOP;
             }
             if (VALID_PID(segment->pids.audio.pid)
               && VALID_PID(p_pids->audio.pid)
               && segment->pids.audio.pid != p_pids->audio.pid) {
               //restart audio
-              a_cmd = DVR_PLAYBACK_CMD_ARESTART;
+              a_cmd = DVR_PLAYBACK_CMD_A_RESTART;
             }
             if (!VALID_PID(segment->pids.audio.pid)
                 && VALID_PID(p_pids->audio.pid)
                 && segment->pids.audio.pid != p_pids->audio.pid) {
                 //start audio
-                a_cmd = DVR_PLAYBACK_CMD_ASTART;
+                a_cmd = DVR_PLAYBACK_CMD_A_START;
             }
             if (VALID_PID(segment->pids.audio.pid)
                 && !VALID_PID(p_pids->audio.pid)
                 && segment->pids.audio.pid != p_pids->audio.pid) {
                 //stop audio
-                a_cmd = DVR_PLAYBACK_CMD_ASTOP;
+                a_cmd = DVR_PLAYBACK_CMD_A_STOP;
             }
             if (a_cmd == DVR_PLAYBACK_CMD_NONE
               && v_cmd == DVR_PLAYBACK_CMD_NONE) {
@@ -2250,41 +2406,41 @@
               player->cmd.cur_cmd = a_cmd != DVR_PLAYBACK_CMD_NONE ? a_cmd : v_cmd;
             } else if (a_cmd != DVR_PLAYBACK_CMD_NONE
               && v_cmd != DVR_PLAYBACK_CMD_NONE) {
-              if (v_cmd == DVR_PLAYBACK_CMD_VRESTART
-                && (a_cmd == DVR_PLAYBACK_CMD_ARESTART)) {
+              if (v_cmd == DVR_PLAYBACK_CMD_V_RESTART
+                && (a_cmd == DVR_PLAYBACK_CMD_A_RESTART)) {
                 player->cmd.last_cmd =DVR_PLAYBACK_CMD_PAUSE;
-                player->cmd.cur_cmd = DVR_PLAYBACK_CMD_AVRESTART;
-              }else if (v_cmd == DVR_PLAYBACK_CMD_VRESTART
-                && a_cmd == DVR_PLAYBACK_CMD_ASTART) {
+                player->cmd.cur_cmd = DVR_PLAYBACK_CMD_AV_RESTART;
+              }else if (v_cmd == DVR_PLAYBACK_CMD_V_RESTART
+                && a_cmd == DVR_PLAYBACK_CMD_A_START) {
                 player->cmd.last_cmd =DVR_PLAYBACK_CMD_PAUSE;
-                player->cmd.cur_cmd = DVR_PLAYBACK_CMD_ASTARTVRESTART;
+                player->cmd.cur_cmd = DVR_PLAYBACK_CMD_A_START_V_RESTART;
               } else {
                 player->cmd.last_cmd =DVR_PLAYBACK_CMD_PAUSE;
-                player->cmd.cur_cmd = DVR_PLAYBACK_CMD_ASTOPVRESTART;
+                player->cmd.cur_cmd = DVR_PLAYBACK_CMD_A_STOP_V_RESTART;
               }
 
-              if (v_cmd == DVR_PLAYBACK_CMD_VSTART
-                && (a_cmd == DVR_PLAYBACK_CMD_ARESTART)) {
+              if (v_cmd == DVR_PLAYBACK_CMD_V_START
+                && (a_cmd == DVR_PLAYBACK_CMD_A_RESTART)) {
                 player->cmd.last_cmd =DVR_PLAYBACK_CMD_PAUSE;
-                player->cmd.cur_cmd = DVR_PLAYBACK_CMD_VSTARTARESTART;
-              } else if (v_cmd == DVR_PLAYBACK_CMD_VSTART
-                && a_cmd == DVR_PLAYBACK_CMD_ASTART) {
+                player->cmd.cur_cmd = DVR_PLAYBACK_CMD_V_START_A_RESTART;
+              } else if (v_cmd == DVR_PLAYBACK_CMD_V_START
+                && a_cmd == DVR_PLAYBACK_CMD_A_START) {
                 //not occur this case
                 player->cmd.last_cmd =DVR_PLAYBACK_CMD_PAUSE;
                 player->cmd.cur_cmd = DVR_PLAYBACK_CMD_START;
               } else {
                 player->cmd.last_cmd =DVR_PLAYBACK_CMD_PAUSE;
-                player->cmd.cur_cmd = DVR_PLAYBACK_CMD_ASTOPVSTART;
+                player->cmd.cur_cmd = DVR_PLAYBACK_CMD_A_STOP_V_START;
               }
 
-              if (v_cmd == DVR_PLAYBACK_CMD_VSTOP
-                && a_cmd == DVR_PLAYBACK_CMD_ASTART) {
+              if (v_cmd == DVR_PLAYBACK_CMD_V_STOP
+                && a_cmd == DVR_PLAYBACK_CMD_A_START) {
                 player->cmd.last_cmd =DVR_PLAYBACK_CMD_PAUSE;
-                player->cmd.cur_cmd = DVR_PLAYBACK_CMD_VSTOPASTART;
-              } else if (v_cmd == DVR_PLAYBACK_CMD_VSTOP
-                && a_cmd == DVR_PLAYBACK_CMD_ARESTART) {
+                player->cmd.cur_cmd = DVR_PLAYBACK_CMD_V_STOP_A_START;
+              } else if (v_cmd == DVR_PLAYBACK_CMD_V_STOP
+                && a_cmd == DVR_PLAYBACK_CMD_A_RESTART) {
                 player->cmd.last_cmd =DVR_PLAYBACK_CMD_PAUSE;
-                player->cmd.cur_cmd = DVR_PLAYBACK_CMD_VSTOPARESTART;
+                player->cmd.cur_cmd = DVR_PLAYBACK_CMD_V_STOP_A_RESTART;
               } else {
                 //not occur this case
                 player->cmd.last_cmd =DVR_PLAYBACK_CMD_PAUSE;
@@ -2295,14 +2451,14 @@
         memcpy(&player->cur_segment.pids, p_pids, sizeof(DVR_PlaybackPids_t));
       }
       //save pids info
-      DVR_PB_DG(1, ":apid :%d %d", segment->pids.audio.pid, p_pids->audio.pid);
+      DVR_PB_INFO(":apid :%d %d", segment->pids.audio.pid, p_pids->audio.pid);
       memcpy(&segment->pids, p_pids, sizeof(DVR_PlaybackPids_t));
-      DVR_PB_DG(1, ":cp apid :%d %d", segment->pids.audio.pid, p_pids->audio.pid);
+      DVR_PB_INFO(":cp apid :%d %d", segment->pids.audio.pid, p_pids->audio.pid);
       break;
     }
   }
-  DVR_PB_DG(1, "unlock");
-  pthread_mutex_unlock(&player->lock);
+  DVR_PB_DEBUG("unlock");
+  dvr_mutex_unlock(&player->lock);
   return DVR_SUCCESS;
 }
 /**\brief Stop play, will stop video and audio
@@ -2313,23 +2469,23 @@
  */
 int dvr_playback_stop(DVR_PlaybackHandle_t handle, DVR_Bool_t clear) {
   DVR_Playback_t *player = (DVR_Playback_t *) handle;
-  UNDVRUSED(clear);
+  DVR_UNUSED(clear);
   if (player == NULL) {
-    DVR_PB_DG(1, "player is NULL");
+    DVR_PB_INFO("player is NULL");
     return DVR_FAILURE;
   }
   if (player->state == DVR_PLAYBACK_STATE_STOP) {
-    DVR_PB_DG(1, ":playback is stoped");
+    DVR_PB_INFO(":playback is stoped");
     return DVR_SUCCESS;
   }
   if (player->state == DVR_PLAYBACK_STATE_STOP) {
-    DVR_PB_DG(1, ":playback is stoped");
+    DVR_PB_INFO(":playback is stoped");
     return DVR_SUCCESS;
   }
   _stop_playback_thread(handle);
-  DVR_PB_DG(1, "lock");
-  pthread_mutex_lock(&player->lock);
-  DVR_PB_DG(1, ":get lock into stop fast");
+  DVR_PB_DEBUG("lock");
+  dvr_mutex_lock(&player->lock);
+  DVR_PB_INFO(":get lock into stop fast");
   AmTsPlayer_stopFast(player->handle);
   if (player->has_video) {
     AmTsPlayer_resumeVideoDecoding(player->handle);
@@ -2354,12 +2510,12 @@
   player->cmd.last_cmd = player->cmd.cur_cmd;
   player->cmd.cur_cmd = DVR_PLAYBACK_CMD_STOP;
   player->cmd.state = DVR_PLAYBACK_STATE_STOP;
-  player->state = DVR_PLAYBACK_STATE_STOP;
+  DVR_PLAYER_CHANGE_STATE(player,DVR_PLAYBACK_STATE_STOP);
   player->cur_segment_id = UINT64_MAX;
   player->segment_is_open = DVR_FALSE;
-  DVR_PB_DG(1, "unlock");
-  DVR_PB_DG(1, "player->state %s", _dvr_playback_state_toString(player->state));
-  pthread_mutex_unlock(&player->lock);
+  DVR_PB_DEBUG("unlock");
+  DVR_PB_INFO("player->state %s", _dvr_playback_state_toString(player->state));
+  dvr_mutex_unlock(&player->lock);
   return DVR_SUCCESS;
 }
 /**\brief Start play audio
@@ -2369,37 +2525,40 @@
  * \return Error code
  */
 
-int dvr_playback_audio_start(DVR_PlaybackHandle_t handle, am_tsplayer_audio_params *param, am_tsplayer_audio_params *adparam) {
+int dvr_playback_audio_start(DVR_PlaybackHandle_t handle, am_tsplayer_audio_params *param, am_tsplayer_audio_params *ad_param) {
   DVR_Playback_t *player = (DVR_Playback_t *) handle;
 
   if (player == NULL) {
-    DVR_PB_DG(1, "player is NULL");
+    DVR_PB_INFO("player is NULL");
     return DVR_FAILURE;
   }
   _start_playback_thread(handle);
   //start audio and video
-  DVR_PB_DG(1, "lock");
-  pthread_mutex_lock(&player->lock);
+  DVR_PB_DEBUG("lock");
+  dvr_mutex_lock(&player->lock);
 
-  if (VALID_PID(adparam->pid)) {
+  if (VALID_PID(ad_param->pid)) {
     player->has_ad_audio = DVR_TRUE;
-    DVR_PB_DG(1, "start ad audio");
-    AmTsPlayer_setADParams(player->handle, adparam);
+    DVR_PB_INFO("start ad audio");
+    AmTsPlayer_setADParams(player->handle, ad_param);
     AmTsPlayer_enableADMix(player->handle);
   }
   if (VALID_PID(param->pid)) {
-    DVR_PB_DG(1, "start audio");
+    DVR_PB_INFO("start audio");
     player->has_audio = DVR_TRUE;
     AmTsPlayer_setAudioParams(player->handle, param);
+    if (player->audio_presentation_id > -1) {
+      AmTsPlayer_setParams(player->handle, AM_TSPLAYER_KEY_AUDIO_PRESENTATION_ID, &player->audio_presentation_id);
+    }
     AmTsPlayer_startAudioDecoding(player->handle);
   }
 
   player->cmd.last_cmd = player->cmd.cur_cmd;
-  player->cmd.cur_cmd = DVR_PLAYBACK_CMD_ASTART;
+  player->cmd.cur_cmd = DVR_PLAYBACK_CMD_A_START;
   player->cmd.state = DVR_PLAYBACK_STATE_START;
-  player->state = DVR_PLAYBACK_STATE_START;
-  DVR_PB_DG(1, "unlock");
-  pthread_mutex_unlock(&player->lock);
+  DVR_PLAYER_CHANGE_STATE(player,DVR_PLAYBACK_STATE_START);
+  DVR_PB_DEBUG("unlock");
+  dvr_mutex_unlock(&player->lock);
   return DVR_SUCCESS;
 }
 /**\brief Stop play audio
@@ -2411,21 +2570,21 @@
   DVR_Playback_t *player = (DVR_Playback_t *) handle;
 
   if (player == NULL) {
-    DVR_PB_DG(1, "player is NULL");
+    DVR_PB_INFO("player is NULL");
     return DVR_FAILURE;
   }
 
   //playback_device_audio_stop(player->handle);
   if (player->has_video == DVR_FALSE) {
     player->cmd.state = DVR_PLAYBACK_STATE_STOP;
-    player->state = DVR_PLAYBACK_STATE_STOP;
-    //destory thread
+    DVR_PLAYER_CHANGE_STATE(player,DVR_PLAYBACK_STATE_STOP);
+    //destroy thread
     _stop_playback_thread(handle);
   } else {
     //do nothing.video is playing
   }
-  DVR_PB_DG(1, "lock");
-  pthread_mutex_lock(&player->lock);
+  DVR_PB_DEBUG("lock");
+  dvr_mutex_lock(&player->lock);
 
   if (player->has_audio) {
     player->has_audio = DVR_FALSE;
@@ -2438,10 +2597,10 @@
   }
 
   player->cmd.last_cmd = player->cmd.cur_cmd;
-  player->cmd.cur_cmd = DVR_PLAYBACK_CMD_ASTOP;
+  player->cmd.cur_cmd = DVR_PLAYBACK_CMD_A_STOP;
 
-  DVR_PB_DG(1, "unlock");
-  pthread_mutex_unlock(&player->lock);
+  DVR_PB_DEBUG("unlock");
+  dvr_mutex_unlock(&player->lock);
   return DVR_SUCCESS;
 }
 /**\brief Start play video
@@ -2454,14 +2613,14 @@
   DVR_Playback_t *player = (DVR_Playback_t *) handle;
 
   if (player == NULL) {
-    DVR_PB_DG(1, "player is NULL");
+    DVR_PB_INFO("player is NULL");
     return DVR_FAILURE;
   }
 
   _start_playback_thread(handle);
   //start audio and video
-  DVR_PB_DG(1, "lock");
-  pthread_mutex_lock(&player->lock);
+  DVR_PB_DEBUG("lock");
+  dvr_mutex_lock(&player->lock);
   player->has_video = DVR_TRUE;
   AmTsPlayer_setVideoParams(player->handle, param);
   AmTsPlayer_setVideoBlackOut(player->handle, 1);
@@ -2470,16 +2629,16 @@
   //playback_device_video_start(player->handle , param);
   //if set flag is pause live, we need set trick mode
   if ((player->play_flag&DVR_PLAYBACK_STARTED_PAUSEDLIVE) == DVR_PLAYBACK_STARTED_PAUSEDLIVE) {
-    DVR_PB_DG(1, "settrick mode at video start");
+    DVR_PB_INFO("settrick mode at video start");
     AmTsPlayer_setTrickMode(player->handle, AV_VIDEO_TRICK_MODE_PAUSE_NEXT);
     //playback_device_trick_mode(player->handle, 1);
   }
   player->cmd.last_cmd = player->cmd.cur_cmd;
-  player->cmd.cur_cmd = DVR_PLAYBACK_CMD_VSTART;
+  player->cmd.cur_cmd = DVR_PLAYBACK_CMD_V_START;
   player->cmd.state = DVR_PLAYBACK_STATE_START;
-  player->state = DVR_PLAYBACK_STATE_START;
-  DVR_PB_DG(1, "unlock");
-  pthread_mutex_unlock(&player->lock);
+  DVR_PLAYER_CHANGE_STATE(player,DVR_PLAYBACK_STATE_START);
+  DVR_PB_DEBUG("unlock");
+  dvr_mutex_unlock(&player->lock);
   return DVR_SUCCESS;
 }
 /**\brief Stop play video
@@ -2491,21 +2650,21 @@
   DVR_Playback_t *player = (DVR_Playback_t *) handle;
 
   if (player == NULL) {
-    DVR_PB_DG(1, "player is NULL");
+    DVR_PB_INFO("player is NULL");
     return DVR_FAILURE;
   }
 
   if (player->has_audio == DVR_FALSE) {
     player->cmd.state = DVR_PLAYBACK_STATE_STOP;
-    player->state = DVR_PLAYBACK_STATE_STOP;
-    //destory thread
+    DVR_PLAYER_CHANGE_STATE(player,DVR_PLAYBACK_STATE_STOP);
+    //destroy thread
     _stop_playback_thread(handle);
   } else {
     //do nothing.audio is playing
   }
 
-  DVR_PB_DG(1, "lock");
-  pthread_mutex_lock(&player->lock);
+  DVR_PB_DEBUG("lock");
+  dvr_mutex_lock(&player->lock);
 
   player->has_video = DVR_FALSE;
 
@@ -2513,10 +2672,10 @@
   //playback_device_video_stop(player->handle);
 
   player->cmd.last_cmd = player->cmd.cur_cmd;
-  player->cmd.cur_cmd = DVR_PLAYBACK_CMD_VSTOP;
+  player->cmd.cur_cmd = DVR_PLAYBACK_CMD_V_STOP;
 
-  DVR_PB_DG(1, "unlock");
-  pthread_mutex_unlock(&player->lock);
+  DVR_PB_DEBUG("unlock");
+  dvr_mutex_unlock(&player->lock);
   return DVR_SUCCESS;
 }
 /**\brief Pause play
@@ -2527,18 +2686,18 @@
  */
 int dvr_playback_pause(DVR_PlaybackHandle_t handle, DVR_Bool_t flush) {
   DVR_Playback_t *player = (DVR_Playback_t *) handle;
-  UNDVRUSED(flush);
+  DVR_UNUSED(flush);
   if (player == NULL) {
-    DVR_PB_DG(1, "player is NULL");
+    DVR_PB_INFO("player is NULL");
     return DVR_FAILURE;
   }
   if (player->state == DVR_PLAYBACK_STATE_PAUSE ||player->state == DVR_PLAYBACK_STATE_STOP ) {
-    DVR_PB_DG(1, "player state  is [%d] pause or stop", player->state);
+    DVR_PB_INFO("player state  is [%d] pause or stop", player->state);
     return DVR_SUCCESS;
   }
-  DVR_PB_DG(1, "lock");
-  pthread_mutex_lock(&player->lock);
-  DVR_PB_DG(1, "get lock");
+  DVR_PB_DEBUG("lock");
+  dvr_mutex_lock(&player->lock);
+  DVR_PB_DEBUG("get lock");
   if (player->has_video)
     AmTsPlayer_pauseVideoDecoding(player->handle);
   if (player->has_audio)
@@ -2548,15 +2707,15 @@
   if (player->cmd.cur_cmd == DVR_PLAYBACK_CMD_FF ||
     player->cmd.cur_cmd == DVR_PLAYBACK_CMD_FB) {
     player->cmd.state = DVR_PLAYBACK_STATE_PAUSE;
-    player->state = DVR_PLAYBACK_STATE_PAUSE;
+    DVR_PLAYER_CHANGE_STATE(player,DVR_PLAYBACK_STATE_PAUSE);
   } else {
     player->cmd.last_cmd = player->cmd.cur_cmd;
     player->cmd.cur_cmd = DVR_PLAYBACK_CMD_PAUSE;
     player->cmd.state = DVR_PLAYBACK_STATE_PAUSE;
-    player->state = DVR_PLAYBACK_STATE_PAUSE;
+    DVR_PLAYER_CHANGE_STATE(player,DVR_PLAYBACK_STATE_PAUSE);
   }
-  pthread_mutex_unlock(&player->lock);
-  DVR_PB_DG(1, "unlock");
+  dvr_mutex_unlock(&player->lock);
+  DVR_PB_DEBUG("unlock");
 
   return DVR_SUCCESS;
 }
@@ -2567,79 +2726,79 @@
   DVR_Playback_t *player = (DVR_Playback_t *) handle;
 
   if (player == NULL) {
-    DVR_PB_DG(1, "player is NULL");
+    DVR_PB_INFO("player is NULL");
     return DVR_FAILURE;
   }
 
   //get video params and audio params
-  DVR_PB_DG(1, "lock");
-  pthread_mutex_lock(&player->lock);
-  am_tsplayer_video_params vparams;
-  am_tsplayer_audio_params aparams;
-  am_tsplayer_audio_params adparams;
+  DVR_PB_DEBUG("lock");
+  dvr_mutex_lock(&player->lock);
+  am_tsplayer_video_params video_params;
+  am_tsplayer_audio_params audio_params;
+  am_tsplayer_audio_params ad_params;
   uint64_t segmentid = player->cur_segment_id;
 
-  memset(&vparams, 0, sizeof(vparams));
-  memset(&aparams, 0, sizeof(aparams));
+  memset(&video_params, 0, sizeof(video_params));
+  memset(&audio_params, 0, sizeof(audio_params));
 
-  _dvr_playback_get_playinfo(handle, segmentid, &vparams, &aparams, &adparams);
-  DVR_PB_DG(1, "unlock cmd: %d", cmd);
-  pthread_mutex_unlock(&player->lock);
+  _dvr_playback_get_playinfo(handle, segmentid, &video_params, &audio_params, &ad_params);
+  DVR_PB_INFO("unlock cmd: %d", cmd);
+  dvr_mutex_unlock(&player->lock);
 
   switch (cmd) {
-    case DVR_PLAYBACK_CMD_AVRESTART:
+    case DVR_PLAYBACK_CMD_AV_RESTART:
       //av restart
-      DVR_PB_DG(1, "do_cmd avrestart");
+      DVR_PB_INFO("do_cmd av_restart");
       _dvr_playback_replay((DVR_PlaybackHandle_t)player, DVR_FALSE);
       break;
-    case DVR_PLAYBACK_CMD_VRESTART:
+    case DVR_PLAYBACK_CMD_V_RESTART:
       dvr_playback_video_stop((DVR_PlaybackHandle_t)player);
-      dvr_playback_video_start((DVR_PlaybackHandle_t)player, &vparams);
+      dvr_playback_video_start((DVR_PlaybackHandle_t)player, &video_params);
       break;
-    case DVR_PLAYBACK_CMD_VSTART:
-      dvr_playback_video_start((DVR_PlaybackHandle_t)player, &vparams);
+    case DVR_PLAYBACK_CMD_V_START:
+      dvr_playback_video_start((DVR_PlaybackHandle_t)player, &video_params);
       break;
-    case DVR_PLAYBACK_CMD_VSTOP:
+    case DVR_PLAYBACK_CMD_V_STOP:
       dvr_playback_video_stop((DVR_PlaybackHandle_t)player);
       break;
-    case DVR_PLAYBACK_CMD_ARESTART:
+    case DVR_PLAYBACK_CMD_A_RESTART:
       //a restart
       dvr_playback_audio_stop((DVR_PlaybackHandle_t)player);
-      dvr_playback_audio_start((DVR_PlaybackHandle_t)player, &aparams, &adparams);
+      dvr_playback_audio_start((DVR_PlaybackHandle_t)player, &audio_params, &ad_params);
       break;
-    case DVR_PLAYBACK_CMD_ASTART:
-      dvr_playback_audio_start((DVR_PlaybackHandle_t)player, &aparams, &adparams);
+    case DVR_PLAYBACK_CMD_A_START:
+      dvr_playback_audio_start((DVR_PlaybackHandle_t)player, &audio_params, &ad_params);
       break;
-    case DVR_PLAYBACK_CMD_ASTOP:
+    case DVR_PLAYBACK_CMD_A_STOP:
       dvr_playback_audio_stop((DVR_PlaybackHandle_t)player);
       break;
-    case  DVR_PLAYBACK_CMD_ASTOPVRESTART:
+    case  DVR_PLAYBACK_CMD_A_STOP_V_RESTART:
       dvr_playback_audio_stop((DVR_PlaybackHandle_t)player);
       dvr_playback_video_stop((DVR_PlaybackHandle_t)player);
-      dvr_playback_video_start((DVR_PlaybackHandle_t)player, &vparams);
+      dvr_playback_video_start((DVR_PlaybackHandle_t)player, &video_params);
       break;
-    case DVR_PLAYBACK_CMD_ASTOPVSTART:
+    case DVR_PLAYBACK_CMD_A_STOP_V_START:
       dvr_playback_audio_stop((DVR_PlaybackHandle_t)player);
-      dvr_playback_video_start((DVR_PlaybackHandle_t)player, &vparams);
+      dvr_playback_video_start((DVR_PlaybackHandle_t)player, &video_params);
       break;
-    case DVR_PLAYBACK_CMD_VSTOPARESTART:
+    case DVR_PLAYBACK_CMD_V_STOP_A_RESTART:
       dvr_playback_video_stop((DVR_PlaybackHandle_t)player);
       dvr_playback_audio_stop((DVR_PlaybackHandle_t)player);
-      dvr_playback_audio_start((DVR_PlaybackHandle_t)player, &aparams, &adparams);
+      dvr_playback_audio_start((DVR_PlaybackHandle_t)player, &audio_params, &ad_params);
       break;
     case DVR_PLAYBACK_CMD_STOP:
       break;
     case DVR_PLAYBACK_CMD_START:
       break;
-    case DVR_PLAYBACK_CMD_ASTARTVRESTART:
+    case DVR_PLAYBACK_CMD_A_START_V_RESTART:
       dvr_playback_video_stop((DVR_PlaybackHandle_t)player);
-      dvr_playback_video_start((DVR_PlaybackHandle_t)player, &vparams);
-      dvr_playback_audio_start((DVR_PlaybackHandle_t)player, &aparams, &adparams);
+      dvr_playback_video_start((DVR_PlaybackHandle_t)player, &video_params);
+      dvr_playback_audio_start((DVR_PlaybackHandle_t)player, &audio_params, &ad_params);
       break;
-    case DVR_PLAYBACK_CMD_VSTARTARESTART:
+    case DVR_PLAYBACK_CMD_V_START_A_RESTART:
       dvr_playback_audio_stop((DVR_PlaybackHandle_t)player);
-      dvr_playback_video_start((DVR_PlaybackHandle_t)player, &vparams);
-      dvr_playback_audio_start((DVR_PlaybackHandle_t)player, &aparams, &adparams);
+      dvr_playback_video_start((DVR_PlaybackHandle_t)player, &video_params);
+      dvr_playback_audio_start((DVR_PlaybackHandle_t)player, &audio_params, &ad_params);
       break;
     case DVR_PLAYBACK_CMD_FF:
     case DVR_PLAYBACK_CMD_FB:
@@ -2661,28 +2820,28 @@
   uint32_t pos = 0;
   uint64_t segmentid = 0;
   if (player == NULL) {
-    DVR_PB_DG(1, "player is NULL");
+    DVR_PB_INFO("player is NULL");
     return DVR_FAILURE;
   }
 
   if (dvr_playback_check_limit(handle)) {
     //get id and pos to check if we can seek to this pos
-    DVR_PB_DG(1, "player start calculate time");
+    DVR_PB_INFO("player start calculate time");
     dvr_playback_calculate_last_valid_segment(handle, &segmentid, &pos);
     if (segmentid != player->cur_segment_id ||
         (segmentid == player->cur_segment_id &&
         pos > _dvr_get_cur_time(handle))) {
         //first to seek new pos and to resume
-        DVR_PB_DG(1, "seek new pos and to resume");
+        DVR_PB_INFO("seek new pos and to resume");
         dvr_playback_seek(handle, segmentid, pos);
     }
   } else {
-    DVR_PB_DG(1, "player is not set limit");
+    DVR_PB_INFO("player is not set limit");
   }
 
   if (player->cmd.cur_cmd == DVR_PLAYBACK_CMD_PAUSE) {
-    DVR_PB_DG(1, "lock");
-    pthread_mutex_lock(&player->lock);
+    DVR_PB_DEBUG("lock");
+    dvr_mutex_lock(&player->lock);
     player->first_frame = 0;
     if (player->has_video)
           AmTsPlayer_pauseVideoDecoding(player->handle);
@@ -2690,7 +2849,7 @@
           AmTsPlayer_pauseAudioDecoding(player->handle);
 
     if (player->has_video) {
-      DVR_PB_DG(1, "dvr_playback_resume set trick mode none");
+      DVR_PB_INFO("dvr_playback_resume set trick mode none");
       AmTsPlayer_setTrickMode(player->handle, AV_VIDEO_TRICK_MODE_NONE);
       AmTsPlayer_resumeVideoDecoding(player->handle);
     }
@@ -2701,45 +2860,50 @@
     //we will stop audio when ff fb, if reach end, we will pause.so we need
     //start audio when resume play
 
-    am_tsplayer_video_params vparams;
-    am_tsplayer_audio_params aparams;
-    am_tsplayer_audio_params adparams;
+    am_tsplayer_video_params video_params;
+    am_tsplayer_audio_params audio_params;
+    am_tsplayer_audio_params ad_params;
     uint64_t segmentid = player->cur_segment_id;
 
-    memset(&vparams, 0, sizeof(vparams));
-    memset(&aparams, 0, sizeof(aparams));
-    _dvr_playback_get_playinfo(handle, segmentid, &vparams, &aparams, &adparams);
+    memset(&video_params, 0, sizeof(video_params));
+    memset(&audio_params, 0, sizeof(audio_params));
+    _dvr_playback_get_playinfo(handle, segmentid, &video_params, &audio_params, &ad_params);
     //valid audio pid, start audio
-    if (player->has_ad_audio == DVR_FALSE && VALID_PID(adparams.pid) && (player->cmd.speed.speed.speed == PLAYBACK_SPEED_X1)) {
+    if (player->has_ad_audio == DVR_FALSE && VALID_PID(ad_params.pid) && (player->cmd.speed.speed.speed == PLAYBACK_SPEED_X1)) {
       player->has_ad_audio = DVR_TRUE;
-      DVR_PB_DG(1, "start ad audio");
-      dvr_playback_change_seek_state(handle, adparams.pid);
-      AmTsPlayer_setADParams(player->handle,  &adparams);
+      DVR_PB_INFO("start ad audio");
+      dvr_playback_change_seek_state(handle, ad_params.pid);
+      AmTsPlayer_setADParams(player->handle,  &ad_params);
       AmTsPlayer_enableADMix(player->handle);
     }
 
-    if (player->has_audio == DVR_FALSE && VALID_PID(aparams.pid) && (player->cmd.speed.speed.speed == PLAYBACK_SPEED_X1)) {
+    if (player->has_audio == DVR_FALSE && VALID_PID(audio_params.pid) && (player->cmd.speed.speed.speed == PLAYBACK_SPEED_X1)) {
       player->has_audio = DVR_TRUE;
-      dvr_playback_change_seek_state(handle, aparams.pid);
-      AmTsPlayer_setAudioParams(player->handle, &aparams);
+      dvr_playback_change_seek_state(handle, audio_params.pid);
+      AmTsPlayer_setAudioParams(player->handle, &audio_params);
+      if (player->audio_presentation_id > -1) {
+        AmTsPlayer_setParams(player->handle, AM_TSPLAYER_KEY_AUDIO_PRESENTATION_ID, &player->audio_presentation_id);
+      }
       AmTsPlayer_startAudioDecoding(player->handle);
     } else {
-      DVR_PB_DG(1, "aparams.pid:%d player->has_audio:%d speed:%d", aparams.pid, player->has_audio, player->cmd.speed.speed.speed);
+      DVR_PB_INFO("audio_params.pid:%d player->has_audio:%d speed:%d", audio_params.pid, player->has_audio, player->cmd.speed.speed.speed);
     }
 
     if (player->cmd.cur_cmd == DVR_PLAYBACK_CMD_FF ||
       player->cmd.cur_cmd == DVR_PLAYBACK_CMD_FB) {
       player->cmd.state = DVR_PLAYBACK_STATE_START;
-      player->state = DVR_PLAYBACK_STATE_START;
+      DVR_PLAYER_CHANGE_STATE(player,DVR_PLAYBACK_STATE_START);
     } else {
       player->cmd.last_cmd = player->cmd.cur_cmd;
       player->cmd.cur_cmd = DVR_PLAYBACK_CMD_RESUME;
       player->cmd.state = DVR_PLAYBACK_STATE_START;
-      player->state = DVR_PLAYBACK_STATE_START;
+      DVR_PLAYER_CHANGE_STATE(player,DVR_PLAYBACK_STATE_START);
     }
-    DVR_PB_DG(1, "unlock");
-    pthread_mutex_unlock(&player->lock);
+    DVR_PB_DEBUG("unlock");
+    dvr_mutex_unlock(&player->lock);
   } else if (player->state == DVR_PLAYBACK_STATE_PAUSE){
+    DVR_PB_INFO("lock");
+    dvr_mutex_lock(&player->lock);
     player->first_frame = 0;
     if (player->has_video)
           AmTsPlayer_pauseVideoDecoding(player->handle);
@@ -2747,29 +2911,31 @@
           AmTsPlayer_pauseAudioDecoding(player->handle);
 
     if (player->has_video) {
-      DVR_PB_DG(1, "dvr_playback_resume set trick mode none 1");
+      DVR_PB_INFO("dvr_playback_resume set trick mode none 1");
       AmTsPlayer_setTrickMode(player->handle, AV_VIDEO_TRICK_MODE_NONE);
       AmTsPlayer_resumeVideoDecoding(player->handle);
     }
     if (player->has_audio)
       AmTsPlayer_resumeAudioDecoding(player->handle);
-    DVR_PB_DG(1, "set start state cur cmd[%d]", player->cmd.cur_cmd);
-    player->cmd.state = DVR_PLAYBACK_STATE_START;
-    player->state = DVR_PLAYBACK_STATE_START;
+    DVR_PB_INFO("set start state cur cmd[%d]", player->cmd.cur_cmd);
     if (player->cmd.speed.speed.speed == PLAYBACK_SPEED_X1)
       _dvr_cmd(handle, player->cmd.cur_cmd);
+    player->cmd.state = DVR_PLAYBACK_STATE_START;
+    DVR_PLAYER_CHANGE_STATE(player,DVR_PLAYBACK_STATE_START);
+    DVR_PB_INFO("unlock");
+    dvr_mutex_unlock(&player->lock);
   } else {
     if ((player->play_flag&DVR_PLAYBACK_STARTED_PAUSEDLIVE) == DVR_PLAYBACK_STARTED_PAUSEDLIVE)
     {
-      DVR_PB_DG(1, "lock ---\r\n");
-      pthread_mutex_lock(&player->lock);
+      DVR_PB_DEBUG("lock ---\r\n");
+      dvr_mutex_lock(&player->lock);
       player->first_frame = 0;
       if (player->has_video)
           AmTsPlayer_pauseVideoDecoding(player->handle);
       if (player->has_audio)
           AmTsPlayer_pauseAudioDecoding(player->handle);
       //clear flag
-      DVR_PB_DG(1, "clear pause live flag cur cmd[%d]", player->cmd.cur_cmd);
+      DVR_PB_INFO("clear pause live flag cur cmd[%d]", player->cmd.cur_cmd);
       player->play_flag = player->play_flag & (~DVR_PLAYBACK_STARTED_PAUSEDLIVE);
       AmTsPlayer_setTrickMode(player->handle, AV_VIDEO_TRICK_MODE_NONE);
       if (player->has_video) {
@@ -2777,8 +2943,8 @@
       }
       if (player->has_audio)
         AmTsPlayer_resumeAudioDecoding(player->handle);
-      DVR_PB_DG(1, "unlock ---\r\n");
-      pthread_mutex_unlock(&player->lock);
+      DVR_PB_DEBUG("unlock ---\r\n");
+      dvr_mutex_unlock(&player->lock);
     }
   }
   return DVR_SUCCESS;
@@ -2791,6 +2957,10 @@
   DVR_PlaybackSegmentInfo_t *cur_segment = NULL;
   DVR_PlaybackSegmentInfo_t *set_segment = NULL;
 
+  // This error is suppressed as the macro code is picked from kernel.
+  // prefetch() here incurring self_assign is used to avoid some compiling
+  // warnings.
+  // coverity[self_assign]
   list_for_each_entry(segment, &player->segment_list, head)
   {
     if (segment->segment_id == segment_id) {
@@ -2804,17 +2974,17 @@
     }
   }
   if (cur_segment == NULL || set_segment == NULL) {
-    DVR_PB_DG(1, "set segmen or cur segment is null");
+    DVR_PB_INFO("set segment or cur segment is null");
     return DVR_TRUE;
   }
   if (cur_segment->pids.video.format != set_segment->pids.video.format ||
     cur_segment->pids.video.pid != set_segment->pids.video.pid ||
     cur_segment->pids.audio.format != set_segment->pids.audio.format ||
     cur_segment->pids.audio.pid != set_segment->pids.audio.pid) {
-    DVR_PB_DG(1, "cur v[%d]a[%d] set v[%d]a[%d]",cur_segment->pids.video.pid,cur_segment->pids.audio.pid,set_segment->pids.video.pid,set_segment->pids.audio.pid);
+    DVR_PB_INFO("cur v[%d]a[%d] set v[%d]a[%d]",cur_segment->pids.video.pid,cur_segment->pids.audio.pid,set_segment->pids.video.pid,set_segment->pids.audio.pid);
     return DVR_TRUE;
   }
-  DVR_PB_DG(1, "play info not change");
+  DVR_PB_INFO("play info not change");
   return DVR_FALSE;
 }
 
@@ -2829,16 +2999,16 @@
 {  DVR_Playback_t *player = (DVR_Playback_t *) handle;
 
   if (player == NULL) {
-    DVR_PB_DG(1, "player is NULL");
+    DVR_PB_INFO("player is NULL");
     return DVR_FAILURE;
   }
   _dvr_getClock_sec();
-  DVR_PB_DG(1, "lock time %lu limit: %u player->state:%d", time, limit, player->state);
-  pthread_mutex_lock(&player->lock);
+  DVR_PB_INFO("lock time %lu limit: %u player->state:%d", time, limit, player->state);
+  dvr_mutex_lock(&player->lock);
   player->rec_start = time;
   player->limit = limit;
-  DVR_PB_DG(1, "unlock ---\r\n");
-  pthread_mutex_unlock(&player->lock);
+  DVR_PB_DEBUG("unlock ---\r\n");
+  dvr_mutex_unlock(&player->lock);
   return DVR_SUCCESS;
 }
 
@@ -2852,36 +3022,34 @@
   DVR_Playback_t *player = (DVR_Playback_t *) handle;
   int ret = DVR_SUCCESS;
   if (player == NULL) {
-    DVR_PB_DG(1, "player is NULL");
+    DVR_PB_INFO("player is NULL");
     return DVR_FAILURE;
   }
 
-  DVR_PB_DG(1, "lock segment_id %llu cur id %llu time_offset %u cur end: %d player->state:%d", segment_id,player->cur_segment_id, (uint32_t)time_offset, _dvr_get_end_time(handle), player->state);
-  pthread_mutex_lock(&player->lock);
+  DVR_PB_INFO("lock segment_id %llu cur id %llu time_offset %u cur end: %d player->state:%d", segment_id,player->cur_segment_id, (uint32_t)time_offset, _dvr_get_end_time(handle), player->state);
+  dvr_mutex_lock(&player->lock);
 
-  int offset = -1;
   DVR_Bool_t replay = _dvr_check_playinfo_changed(handle, player->cur_segment_id, segment_id);
-  DVR_PB_DG(1, "player->state[%d]-replay[%d]--get lock-", player->state, replay);
+  DVR_PB_INFO("player->state[%d]-replay[%d]--get lock-", player->state, replay);
 
   //open segment if id is not current segment
   ret = _dvr_open_segment(handle, segment_id);
   if (ret ==DVR_FAILURE) {
-    DVR_PB_DG(1, "unlock seek error at open segment");
-    pthread_mutex_unlock(&player->lock);
+    DVR_PB_ERROR("unlock seek error at open segment");
+    dvr_mutex_unlock(&player->lock);
     return DVR_FAILURE;
   }
   if (time_offset >_dvr_get_end_time(handle) &&_dvr_has_next_segmentId(handle, segment_id) == DVR_FAILURE) {
     if (segment_ongoing(player->r_handle) == DVR_SUCCESS) {
-      DVR_PB_DG(1, "is ongoing segment when seek end, need return success");
+      DVR_PB_INFO("is ongoing segment when seek end, need return success");
       time_offset = _dvr_get_end_time(handle);
     } else {
-      DVR_PB_DG(1, "is not ongoing segment when seek end, return failure");
-      time_offset = _dvr_get_end_time(handle);
-      ret = DVR_FAILURE;
+      DVR_PB_ERROR("is not ongoing segment when seek end, return failure");
+      return DVR_FAILURE;
     }
   }
 
-  DVR_PB_DG(1, "seek open id[%lld]flag[0x%x] time_offset %u",
+  DVR_PB_INFO("seek open id[%lld]flag[0x%x] time_offset %u",
   player->cur_segment.segment_id,
   player->cur_segment.flags,
   time_offset);
@@ -2893,21 +3061,23 @@
       time_offset = time_offset -FB_DEFAULT_LEFT_TIME;
     }
   }
+  // Seek can be regarded as a new playback, so keep the start segment_id for it also
   if (player->need_seek_start == DVR_TRUE) {
     player->first_start_time = (uint64_t)time_offset + 1;//set first start time not eq 0
+    player->first_start_id = player->cur_segment.segment_id;
   }
   pthread_mutex_lock(&player->segment_lock);
   player->drop_ts = DVR_TRUE;
   player->ts_cache_len = 0;
-  offset = segment_seek(player->r_handle, (uint64_t)time_offset, player->openParams.block_size);
-  DVR_PB_DG(0, "seek get offset by time offset, offset=%d time_offset %u",offset, time_offset);
+  int offset = segment_seek(player->r_handle, (uint64_t)time_offset, player->openParams.block_size);
+  DVR_PB_ERROR("seek get offset by time offset, offset=%d time_offset %u",offset, time_offset);
   pthread_mutex_unlock(&player->segment_lock);
   player->offset = offset;
 
   _dvr_get_end_time(handle);
 
   player->last_send_time_id = UINT64_MAX;
-  player->last_segment_tatol = 0LL;
+  player->last_segment_total = 0LL;
   player->last_segment_id = 0LL;
   //init fffb time
   player->fffb_current = _dvr_time_getClock();
@@ -2917,12 +3087,12 @@
   //pause state if need to replayer false
   if (player->state == DVR_PLAYBACK_STATE_STOP) {
     //only seek file,not start
-    DVR_PB_DG(1, "unlock");
-    pthread_mutex_unlock(&player->lock);
+    DVR_PB_DEBUG("unlock");
+    dvr_mutex_unlock(&player->lock);
     return DVR_SUCCESS;
   }
   //stop play
-  DVR_PB_DG(0, "seek stop play, not inject data has video[%d]audio[%d]",
+  DVR_PB_ERROR("seek stop play, not inject data has video[%d]audio[%d]",
   player->has_video, player->has_audio);
 
   if (player->has_video) {
@@ -2942,40 +3112,40 @@
   }
 
   //start play
-  am_tsplayer_video_params    vparams;
-  am_tsplayer_audio_params    aparams;
-  am_tsplayer_audio_params    adparams;
+  am_tsplayer_video_params    video_params;
+  am_tsplayer_audio_params    audio_params;
+  am_tsplayer_audio_params    ad_params;
 
-  memset(&vparams, 0, sizeof(vparams));
-  memset(&aparams, 0, sizeof(aparams));
+  memset(&video_params, 0, sizeof(video_params));
+  memset(&audio_params, 0, sizeof(audio_params));
 
   player->cur_segment_id = segment_id;
 
   int sync = DVR_PLAYBACK_SYNC;
   //get segment info and audio video pid fmt ;
-  _dvr_playback_get_playinfo(handle, segment_id, &vparams, &aparams, &adparams);
+  _dvr_playback_get_playinfo(handle, segment_id, &video_params, &audio_params, &ad_params);
   //start audio and video
-  if (vparams.pid != player->fake_pid && !VALID_PID(vparams.pid) && !VALID_PID(aparams.pid)) {
+  if (video_params.pid != player->fake_pid && !VALID_PID(video_params.pid) && !VALID_PID(audio_params.pid)) {
     //audio and video pid is all invalid, return error.
-    DVR_PB_DG(0, "unlock seek start dvr play back start error, not found audio and video info [0x%x]", vparams.pid);
-    pthread_mutex_unlock(&player->lock);
+    DVR_PB_ERROR("unlock seek start dvr play back start error, not found audio and video info [0x%x]", video_params.pid);
+    dvr_mutex_unlock(&player->lock);
     return -1;
   }
-  DVR_PB_DG(0, "seek start[0x%x]", vparams.pid);
+  DVR_PB_ERROR("seek start[0x%x]", video_params.pid);
   //add
   if (sync == DVR_PLAYBACK_SYNC) {
-    if (VALID_PID(vparams.pid)) {
+    if (VALID_PID(video_params.pid)) {
       //player->has_video;
       if (player->cmd.cur_cmd == DVR_PLAYBACK_CMD_PAUSE ||
         player->state == DVR_PLAYBACK_STATE_PAUSE ||
         player->speed > 2.0f||
         player->speed <= -1.0f) {
         //if is pause state. we need set trick mode.
-        DVR_PB_DG(1, "seek set trick mode player->speed [%f]", player->speed);
+        DVR_PB_INFO("seek set trick mode player->speed [%f]", player->speed);
         AmTsPlayer_setTrickMode(player->handle, AV_VIDEO_TRICK_MODE_PAUSE_NEXT);
       }
-      DVR_PB_DG(1, "start video");
-      AmTsPlayer_setVideoParams(player->handle, &vparams);
+      DVR_PB_INFO("start video");
+      AmTsPlayer_setVideoParams(player->handle, &video_params);
       AmTsPlayer_setVideoBlackOut(player->handle, 1);
       AmTsPlayer_startVideoDecoding(player->handle);
       if (IS_KERNEL_SPEED(player->cmd.speed.speed.speed) &&
@@ -2988,57 +3158,69 @@
     } else {
       player->has_video = DVR_FALSE;
     }
-    if (VALID_PID(adparams.pid) && player->speed == 1.0) {
+    if (VALID_PID(ad_params.pid) && player->speed == 1.0) {
       player->has_ad_audio = DVR_TRUE;
-      DVR_PB_DG(1, "start ad audio");
-      dvr_playback_change_seek_state(handle, adparams.pid);
-      AmTsPlayer_setADParams(player->handle,  &adparams);
+      DVR_PB_INFO("start ad audio");
+      dvr_playback_change_seek_state(handle, ad_params.pid);
+      AmTsPlayer_setADParams(player->handle,  &ad_params);
       AmTsPlayer_enableADMix(player->handle);
     }
-    if (VALID_PID(aparams.pid) && player->speed == 1.0) {
-      DVR_PB_DG(1, "start audio seek");
-      dvr_playback_change_seek_state(handle, aparams.pid);
-      AmTsPlayer_setAudioParams(player->handle, &aparams);
+    if (VALID_PID(audio_params.pid) && player->speed == 1.0) {
+      DVR_PB_INFO("start audio seek");
+      dvr_playback_change_seek_state(handle, audio_params.pid);
+      AmTsPlayer_setAudioParams(player->handle, &audio_params);
+      if (player->audio_presentation_id > -1) {
+        AmTsPlayer_setParams(player->handle, AM_TSPLAYER_KEY_AUDIO_PRESENTATION_ID, &player->audio_presentation_id);
+      }
       AmTsPlayer_startAudioDecoding(player->handle);
       player->has_audio = DVR_TRUE;
     }
+#ifdef AVSYNC_USED_PCR
+    if (player && VALID_PID(player->cur_segment.pids.pcr.pid)) {
+      DVR_PB_INFO("start set pcr [%d]", player->cur_segment.pids.pcr.pid);
+      AmTsPlayer_setPcrPid(player->handle, player->cur_segment.pids.pcr.pid);
+    }
+#endif
   }
   if (player->state == DVR_PLAYBACK_STATE_PAUSE) {
     player->cmd.state = DVR_PLAYBACK_STATE_PAUSE;
-    player->state = DVR_PLAYBACK_STATE_PAUSE;
-    if (VALID_PID(aparams.pid) || VALID_PID(vparams.pid))
+    DVR_PLAYER_CHANGE_STATE(player,DVR_PLAYBACK_STATE_PAUSE);
+    if (VALID_PID(audio_params.pid) || VALID_PID(video_params.pid))
       player->seek_pause = DVR_TRUE;
-    DVR_PB_DG(1, "set state pause in seek vpid[0x%x]apid[0x%x]",vparams.pid, aparams.pid);
+    DVR_PB_INFO("set state pause in seek vpid[0x%x]apid[0x%x]",video_params.pid, audio_params.pid);
   } else if (player->cmd.cur_cmd == DVR_PLAYBACK_CMD_FF ||
-    player->cmd.cur_cmd == DVR_PLAYBACK_CMD_FF ||
+    player->cmd.cur_cmd == DVR_PLAYBACK_CMD_FB ||
     player->speed > 1.0f||
     player->speed <= -1.0f) {
-    DVR_PB_DG(1, "not set cmd to seek");
+    DVR_PB_INFO("not set cmd to seek");
     //not pause state, we need not set cur cmd
   } else {
-    DVR_PB_DG(1, "set cmd to seek");
+    DVR_PB_INFO("set cmd to seek");
     player->cmd.last_cmd = player->cmd.cur_cmd;
     player->cmd.cur_cmd = DVR_PLAYBACK_CMD_SEEK;
     player->cmd.state = DVR_PLAYBACK_STATE_START;
-    player->state = DVR_PLAYBACK_STATE_START;
+    DVR_PLAYER_CHANGE_STATE(player,DVR_PLAYBACK_STATE_START);
   }
   player->last_send_time_id = UINT64_MAX;
-  DVR_PB_DG(1, "unlock");
-  pthread_mutex_unlock(&player->lock);
+  DVR_PB_DEBUG("unlock");
+  dvr_mutex_unlock(&player->lock);
 
   return DVR_SUCCESS;
 }
 
+// Get current playback time position of the ongoing segment.
+// Notice the return value may be negative. This is because previous segment's
+// data cached in demux buffer need to be considered.
 static int _dvr_get_cur_time(DVR_PlaybackHandle_t handle) {
   //get cur time of segment
   DVR_Playback_t *player = (DVR_Playback_t *) handle;
 
   if (player == NULL || player->handle == (am_tsplayer_handle)NULL) {
-    DVR_PB_DG(1, "player is NULL");
+    DVR_PB_INFO("player is NULL");
     return DVR_FAILURE;
   }
 
-  int64_t cache = 0;//defalut es buf cache 500ms
+  int64_t cache = 0;//default es buf cache 500ms
   pthread_mutex_lock(&player->segment_lock);
   loff_t pos = segment_tell_position(player->r_handle) -player->ts_cache_len;
   uint64_t cur = 0;
@@ -3051,7 +3233,7 @@
   }
   AmTsPlayer_getDelayTime(player->handle, &cache);
   pthread_mutex_unlock(&player->segment_lock);
-  DVR_PB_DG(1, "get cur time [%lld] cache:%lld cur id [%lld]last id [%lld] pb cache len [%d] [%lld]", cur, cache, player->cur_segment_id,player->last_send_time_id,  player->ts_cache_len, pos);
+  DVR_PB_INFO("get cur time [%lld] cache:%lld cur id [%lld]last id [%lld] pb cache len [%d] [%lld]", cur, cache, player->cur_segment_id,player->last_send_time_id,  player->ts_cache_len, pos);
   if (player->state == DVR_PLAYBACK_STATE_STOP) {
     cache = 0;
   }
@@ -3059,52 +3241,76 @@
   return cur_time;
 }
 
+// Get current playback time position of the ongoing segment.
+// Notice the return value may be negative. This is because previous segment's
+// data cached in demux buffer need to be considered.
 static int _dvr_get_play_cur_time(DVR_PlaybackHandle_t handle, uint64_t *id) {
   //get cur time of segment
   DVR_Playback_t *player = (DVR_Playback_t *) handle;
 
   if (player == NULL || player->handle == 0) {
-    DVR_PB_DG(1, "player is NULL");
+    DVR_PB_INFO("player is NULL");
     return DVR_FAILURE;
   }
 
-  int64_t cache = 0;//defalut es buf cache 500ms
+  int64_t cache = 0;//default es buf cache 500ms
   int cur_time = 0;
   pthread_mutex_lock(&player->segment_lock);
-  loff_t tmp_pos = segment_tell_position(player->r_handle);
-  loff_t pos = tmp_pos - player->ts_cache_len;
+  loff_t pos = segment_tell_position(player->r_handle);
   uint64_t cur = 0;
-  if (player->ts_cache_len > 0 && (tmp_pos < player->ts_cache_len)) {
+  if (player->ts_cache_len > 0 && (pos < 0)) {
     //this case is open new segment end,but cache data is last segment.
     //we need used last segment len to send play time.
     cur = 0;
-    DVR_PB_DG(1, "change segment [%lld][%lld]", player->last_segment_id, player->cur_segment_id);
+    DVR_PB_INFO("change segment [%lld][%lld]",
+                  player->last_segment_id, player->cur_segment_id);
   } else {
     cur = segment_tell_position_time(player->r_handle, pos);
   }
   AmTsPlayer_getDelayTime(player->handle, &cache);
+
   pthread_mutex_unlock(&player->segment_lock);
-  DVR_PB_DG(1, "***get play cur time [%lld] cache:%lld cur id [%lld]last id [%lld] pb cache len [%d] [%lld][%lld]", cur, cache, player->cur_segment_id,player->last_send_time_id,  player->ts_cache_len, pos, tmp_pos);
+
+  // The idea here is to work around a weakness of AmTsPlayer_getDelayTime at
+  // starting phase of a playback in a short period of 20ms or less. During the
+  // said period, getDelayTime does NOT work as expect to return real cache
+  // length because demux isn't actually running to provide valid pts to
+  // TsPlayer. "cache==0" implies the situation that playback is NOT actually
+  // started. Under such conditions a '0' cache size may NOT reflect actual data
+  // length remaining in TsPlayer cache, therefore corresponding libdvr 'cur' is
+  // useless if data in TsPlayer cache is not considered, so it needs to be
+  // reset to a previous valid state. To make the reset operation stricter, extra
+  // AmTsPlayer_getPts invocations on both video/audio are introduced to test if
+  // TsPlayer can get valid pts which indicates the actual running status of
+  // demux. (JIRA issue: SWPL-68740)
+  if (player->first_start_id != UINT64_MAX && cache == 0
+          && player->check_cache_flag == DVR_TRUE ) {
+    uint64_t pts_a=0;
+    uint64_t pts_v=0;
+    AmTsPlayer_getPts(player->handle, TS_STREAM_AUDIO, &pts_a);
+    AmTsPlayer_getPts(player->handle, TS_STREAM_VIDEO, &pts_v);
+    if ((int64_t)pts_a <= 0 && (int64_t)pts_v <= 0) {
+      // Identified the wired situation and just return previous valid state
+      cur = player->first_start_time;
+      *id = player->first_start_id;
+      return cur;
+    }
+  }
+  if (cache != 0) {
+    // Do NOT permit to enter 'if' code block above any more
+    player->check_cache_flag=DVR_FALSE;
+  }
+
   if (player->state == DVR_PLAYBACK_STATE_STOP) {
     cache = 0;
   }
-  if (cur > cache) {
-      cur_time = (int)(cur - cache);
-      *id =  player->cur_segment_id;
-  } else if (player->last_segment_tatol > 0) {
+  cur_time = (int)(cur - cache);
+  *id =  player->cur_segment_id;
 
-      if (player->last_segment_tatol > (cache - cur))
-        cur_time = (int)(player->last_segment_tatol - (cache - cur));
-      else
-        cur_time = (int)(player->last_segment_tatol - cur);
-
-      *id = player->last_segment_id;
-      DVR_PB_DG(1, "get play cur time[%lld][%lld][%d]", player->last_segment_id, player->cur_segment_id, player->last_segment_tatol);
-  } else {
-      cur_time = 0;
-      *id =  player->cur_segment_id;
-  }
-
+  DVR_PB_INFO("***get playback slider position within segment. segment_id [%lld],"
+      " segment_slider_pos[%7d ms] = segment_read_pos[%7lld ms] - tsplayer_cache_len[%5lld ms],"
+      " last id [%lld] pos [%lld]",
+      player->cur_segment_id,cur_time,cur,cache,player->last_send_time_id,pos);
   return cur_time;
 }
 
@@ -3114,13 +3320,13 @@
   DVR_Playback_t *player = (DVR_Playback_t *) handle;
 
   if (player == NULL) {
-    DVR_PB_DG(1, "player is NULL");
+    DVR_PB_INFO("player is NULL");
     return DVR_FAILURE;
   }
 
   pthread_mutex_lock(&player->segment_lock);
   uint64_t end = segment_tell_total_time(player->r_handle);
-  DVR_PB_DG(1, "get tatal time [%lld]", end);
+  DVR_PB_INFO("get total time [%lld]", end);
   pthread_mutex_unlock(&player->segment_lock);
   return (int)end;
 }
@@ -3131,7 +3337,7 @@
   DVR_Playback_t *player = (DVR_Playback_t *) handle;
 
   if (player == NULL) {
-    DVR_PB_DG(1, "player is NULL");
+    DVR_PB_INFO("player is NULL");
     return DVR_FALSE;
   }
   if (player->rec_start > 0 || player->limit > 0) {
@@ -3153,11 +3359,11 @@
   uint32_t tmp_time;
   uint32_t expired = 0;
   if (player == NULL) {
-    DVR_PB_DG(1, "player is NULL");
+    DVR_PB_INFO("player is NULL");
     return expired;
   }
   if (player->rec_start == 0 || player->limit == 0) {
-    DVR_PB_DG(1, "rec limit 0");
+    DVR_PB_INFO("rec limit 0");
     return expired;
   }
   //get system time
@@ -3165,7 +3371,7 @@
   if ((cur_time - player->rec_start) > player->limit) {
     tmp_time = (uint32_t)((cur_time - player->rec_start) - player->limit) * 1000U;
     expired = *(int*)&tmp_time;
-    DVR_PB_DG(1, "cur_time:%u, rec start:%u limit:%d c_r_diff:%u expired:%u tmp_time:%u",
+    DVR_PB_INFO("cur_time:%u, rec start:%u limit:%d c_r_diff:%u expired:%u tmp_time:%u",
                 cur_time,
                 player->rec_start,
                 player->limit,
@@ -3187,15 +3393,15 @@
   DVR_Playback_t *player = (DVR_Playback_t *) handle;
 
   if (player == NULL) {
-    DVR_PB_DG(1, "player is NULL");
+    DVR_PB_INFO("player is NULL");
     return DVR_FALSE;
   }
   //get system time
-  DVR_PB_DG(1, "lock ---\r\n");
-  pthread_mutex_lock(&player->lock);
+  DVR_PB_DEBUG("lock ---\r\n");
+  dvr_mutex_lock(&player->lock);
   player->obsolete = obsolete;
-  DVR_PB_DG(1, "unlock ---\r\n");
-  pthread_mutex_unlock(&player->lock);
+  DVR_PB_DEBUG("unlock ---\r\n");
+  dvr_mutex_unlock(&player->lock);
   return expired;
 }
 
@@ -3214,10 +3420,14 @@
   DVR_PlaybackSegmentInfo_t *pre_segment = NULL;
 
   if (player == NULL) {
-    DVR_PB_DG(1, " player is NULL");
+    DVR_PB_INFO(" player is NULL");
     return DVR_FAILURE;
   }
   //update the newest segment duration on timeshift mode
+  // This error is suppressed as the macro code is picked from kernel.
+  // prefetch() here incurring self_assign is used to avoid some compiling
+  // warnings.
+  // coverity[self_assign]
   list_for_each_entry(segment, &player->segment_list, head)
   {
     if (segment->segment_id == segmentid) {
@@ -3241,7 +3451,7 @@
   DVR_Playback_t *player = (DVR_Playback_t *) handle;
 
   if (player == NULL) {
-    DVR_PB_DG(1, "player is NULL");
+    DVR_PB_INFO("player is NULL");
     return DVR_FAILURE;
   }
   expired = dvr_playback_calculate_expiredlen(handle);
@@ -3250,15 +3460,19 @@
     *pos       = 0;
     return DVR_SUCCESS;
   }
-  DVR_PlaybackSegmentInfo_t *pseg;
-  list_for_each_entry_reverse(pseg, &player->segment_list, head) {
-    segment_id = pseg->segment_id;
+  DVR_PlaybackSegmentInfo_t *p_seg;
+  // This error is suppressed as the macro code is picked from kernel.
+  // prefetch() here incurring self_assign is used to avoid some compiling
+  // warnings.
+  // coverity[self_assign]
+  list_for_each_entry_reverse(p_seg, &player->segment_list, head) {
+    segment_id = p_seg->segment_id;
 
-    if ((player->obsolete + pre_off + pseg->duration) > expired)
+    if ((player->obsolete + pre_off + p_seg->duration) > expired)
         break;
 
-    last_segment_id = pseg->segment_id;
-    pre_off += pseg->duration;
+    last_segment_id = p_seg->segment_id;
+    pre_off += p_seg->duration;
   }
 
   if (last_segment_id == segment_id) {
@@ -3285,7 +3499,7 @@
   uint64_t segmentid = 0;
   int pos = 0;
   if (player == NULL) {
-    DVR_PB_DG(1, "player is NULL");
+    DVR_PB_INFO("player is NULL");
     return DVR_FAILURE;
   }
 
@@ -3295,9 +3509,8 @@
     player->fffb_current = player->fffb_start;
     //get segment current time pos
     player->fffb_start_pcr = _dvr_get_cur_time(handle);
-    DVR_PB_DG(1, "calculate seek pos player->fffb_start_pcr[%d]ms, speed[%f]",
+    DVR_PB_INFO("calculate seek pos player->fffb_start_pcr[%d]ms, speed[%f]",
                   player->fffb_start_pcr, player->speed);
-    t_diff = 0;
     //default first time 2s seek
     seek_time = FB_MIX_SEEK_TIME;
   } else {
@@ -3315,7 +3528,7 @@
       player->ts_cache_len = 0;
       if (seek_time < FB_MIX_SEEK_TIME && IS_FB(player->speed)) {
         //set seek time to 0;
-        DVR_PB_DG(1, "segment seek to 0 at fb mode [%d]id[%lld]",
+        DVR_PB_INFO("segment seek to 0 at fb mode [%d]id[%lld]",
                       seek_time,
                       player->cur_segment_id);
         seek_time = 0;
@@ -3348,9 +3561,9 @@
       pthread_mutex_unlock(&player->segment_lock);
     } else {
       //
-      DVR_PB_DG(1, "segment not open,can not seek");
+      DVR_PB_INFO("segment not open,can not seek");
     }
-    DVR_PB_DG(1, "calculate seek pos seek_time[%d]ms, speed[%f]id[%lld]cur [%d]",
+    DVR_PB_INFO("calculate seek pos seek_time[%d]ms, speed[%f]id[%lld]cur [%d]",
                   seek_time,
                   player->speed,
                   player->cur_segment_id,
@@ -3366,64 +3579,64 @@
   DVR_Playback_t *player = (DVR_Playback_t *) handle;
 
   if (player == NULL) {
-    DVR_PB_DG(1, "player is NULL");
+    DVR_PB_INFO("player is NULL");
     return DVR_FAILURE;
   }
 
   //stop
   if (player->has_video) {
-    DVR_PB_DG(1, "fffb stop video");
+    DVR_PB_INFO("fffb stop video");
     AmTsPlayer_setVideoBlackOut(player->handle, 0);
     AmTsPlayer_stopVideoDecoding(player->handle);
   }
   if (player->has_audio) {
-    DVR_PB_DG(1, "fffb stop audio");
+    DVR_PB_INFO("fffb stop audio");
     player->has_audio =DVR_FALSE;
     AmTsPlayer_stopAudioDecoding(player->handle);
   }
   if (player->has_ad_audio) {
-    DVR_PB_DG(1, "fffb stop audio");
+    DVR_PB_INFO("fffb stop audio");
     player->has_ad_audio =DVR_FALSE;
     AmTsPlayer_disableADMix(player->handle);
   }
 
   //start video and audio
 
-  am_tsplayer_video_params    vparams;
-  am_tsplayer_audio_params    aparams;
-  am_tsplayer_audio_params    adparams;
+  am_tsplayer_video_params    video_params;
+  am_tsplayer_audio_params    audio_params;
+  am_tsplayer_audio_params    ad_params;
 
-  memset(&vparams, 0, sizeof(vparams));
-  memset(&aparams, 0, sizeof(aparams));
+  memset(&video_params, 0, sizeof(video_params));
+  memset(&audio_params, 0, sizeof(audio_params));
 
   uint64_t segment_id = player->cur_segment_id;
 
   //get segment info and audio video pid fmt ;
-  //pthread_mutex_lock(&player->lock);
-  _dvr_playback_get_playinfo(handle, segment_id, &vparams, &aparams, &adparams);
+  //dvr_mutex_lock(&player->lock);
+  _dvr_playback_get_playinfo(handle, segment_id, &video_params, &audio_params, &ad_params);
   //start audio and video
-  if (!VALID_PID(vparams.pid) && !VALID_PID(aparams.pid)) {
-    //audio abnd video pis is all invalid, return error.
-    DVR_PB_DG(0, "dvr play back restart error, not found audio and video info");
+  if (!VALID_PID(video_params.pid) && !VALID_PID(audio_params.pid)) {
+    //audio and video pids are all invalid, return error.
+    DVR_PB_ERROR("dvr play back restart error, not found audio and video info");
     return -1;
   }
 
-  if (VALID_PID(vparams.pid)) {
+  if (VALID_PID(video_params.pid)) {
     player->has_video = DVR_TRUE;
-    DVR_PB_DG(1, "fffb start video");
-    //DVR_PB_DG(1, "fffb start video and save last frame");
+    DVR_PB_INFO("fffb start video");
+    //DVR_PB_INFO("fffb start video and save last frame");
     //AmTsPlayer_setVideoBlackOut(player->handle, 0);
     AmTsPlayer_setTrickMode(player->handle, AV_VIDEO_TRICK_MODE_NONE);
     AmTsPlayer_setTrickMode(player->handle, AV_VIDEO_TRICK_MODE_PAUSE_NEXT);
-    AmTsPlayer_setVideoParams(player->handle, &vparams);
+    AmTsPlayer_setVideoParams(player->handle, &video_params);
     AmTsPlayer_setVideoBlackOut(player->handle, 1);
     AmTsPlayer_startVideoDecoding(player->handle);
-    //playback_device_video_start(player->handle , &vparams);
+    //playback_device_video_start(player->handle , &video_params);
     //if set flag is pause live, we need set trick mode
     //playback_device_trick_mode(player->handle, 1);
   }
   //fffb mode need stop fast;
-  DVR_PB_DG(1, "stop fast");
+  DVR_PB_INFO("stop fast");
   AmTsPlayer_stopFast(player->handle);
   return 0;
 }
@@ -3431,16 +3644,16 @@
 static int _dvr_playback_fffb(DVR_PlaybackHandle_t handle) {
   DVR_Playback_t *player = (DVR_Playback_t *) handle;
   if (player == NULL) {
-    DVR_PB_DG(1, "player is NULL");
+    DVR_PB_INFO("player is NULL");
     return DVR_FAILURE;
   }
 
   player->first_frame = 0;
-  DVR_PB_DG(1, "lock  speed [%f]", player->speed);
-  pthread_mutex_lock(&player->lock);
+  DVR_PB_INFO("lock  speed [%f]", player->speed);
+  dvr_mutex_lock(&player->lock);
 
   int seek_time = _dvr_playback_calculate_seekpos(handle);
-  DVR_PB_DG(1, "get lock  speed [%f]id [%lld]seek_time[%d]", player->speed, player->cur_segment_id, seek_time);
+  DVR_PB_INFO("get lock  speed [%f]id [%lld]seek_time[%d]", player->speed, player->cur_segment_id, seek_time);
 
   if (_dvr_has_next_segmentId(handle, player->cur_segment_id) == DVR_FAILURE && seek_time < FB_MIX_SEEK_TIME && IS_FB(player->speed)) {
       //seek time set 0
@@ -3450,8 +3663,8 @@
     //for fb cmd, we need open pre segment.if reach first one segment, send begin event
     int ret = _change_to_next_segment((DVR_PlaybackHandle_t)player);
     if (ret != DVR_SUCCESS && IS_FB(player->speed)) {
-      pthread_mutex_unlock(&player->lock);
-      DVR_PB_DG(1, "unlock");
+      dvr_mutex_unlock(&player->lock);
+      DVR_PB_DEBUG("unlock");
       dvr_playback_pause(handle, DVR_FALSE);
       //send event here and pause
       DVR_Play_Notify_t notify;
@@ -3459,19 +3672,19 @@
       notify.event = DVR_PLAYBACK_EVENT_REACHED_BEGIN;
       //get play statue not here
       _dvr_playback_sent_event(handle, DVR_PLAYBACK_EVENT_REACHED_BEGIN, &notify, DVR_TRUE);
-      DVR_PB_DG(1, "*******************send begin event  speed [%f] cur [%d]", player->speed, _dvr_get_cur_time(handle));
+      DVR_PB_INFO("*******************send begin event  speed [%f] cur [%d]", player->speed, _dvr_get_cur_time(handle));
       //change to pause
       return DVR_SUCCESS;
     }
     _dvr_playback_sent_transition_ok(handle, DVR_FALSE);
     _dvr_init_fffb_time(handle);
-    DVR_PB_DG(1, "*******************send trans ok event  speed [%f]", player->speed);
+    DVR_PB_INFO("*******************send trans ok event  speed [%f]", player->speed);
   }
   player->next_fffb_time =_dvr_time_getClock() + FFFB_SLEEP_TIME;
   _dvr_playback_fffb_replay(handle);
 
-  pthread_mutex_unlock(&player->lock);
-  DVR_PB_DG(1, "unlock");
+  dvr_mutex_unlock(&player->lock);
+  DVR_PB_DEBUG("unlock");
 
   return DVR_SUCCESS;
 }
@@ -3482,7 +3695,7 @@
   DVR_Playback_t *player = (DVR_Playback_t *) handle;
 
   if (player == NULL) {
-    DVR_PB_DG(1, "player is NULL");
+    DVR_PB_INFO("player is NULL");
     return DVR_FAILURE;
   }
 
@@ -3499,65 +3712,74 @@
   }
   //start video and audio
 
-  am_tsplayer_video_params    vparams;
-  am_tsplayer_audio_params    aparams;
-  am_tsplayer_audio_params    adparams;
+  am_tsplayer_video_params    video_params;
+  am_tsplayer_audio_params    audio_params;
+  am_tsplayer_audio_params    ad_params;
   uint64_t segment_id = player->cur_segment_id;
 
-  memset(&vparams, 0, sizeof(vparams));
-  memset(&aparams, 0, sizeof(aparams));
+  memset(&video_params, 0, sizeof(video_params));
+  memset(&audio_params, 0, sizeof(audio_params));
 
   //get segment info and audio video pid fmt ;
-  DVR_PB_DG(1, "into");
-  _dvr_playback_get_playinfo(handle, segment_id, &vparams, &aparams, &adparams);
+  DVR_PB_INFO("into");
+  _dvr_playback_get_playinfo(handle, segment_id, &video_params, &audio_params, &ad_params);
   //start audio and video
-  if (!VALID_PID(vparams.pid) && !VALID_PID(aparams.pid)) {
+  if (!VALID_PID(video_params.pid) && !VALID_PID(audio_params.pid)) {
     //audio and video pis is all invalid, return error.
-    DVR_PB_DG(0, "dvr play back restart error, not found audio and video info");
+    DVR_PB_ERROR("dvr play back restart error, not found audio and video info");
     return -1;
   }
 
-  if (VALID_PID(vparams.pid)) {
+  if (VALID_PID(video_params.pid)) {
     player->has_video = DVR_TRUE;
     if (trick == DVR_TRUE) {
-      DVR_PB_DG(1, "settrick mode at replay");
+      DVR_PB_INFO("settrick mode at replay");
       AmTsPlayer_setTrickMode(player->handle, AV_VIDEO_TRICK_MODE_PAUSE_NEXT);
     }
     else {
       AmTsPlayer_setTrickMode(player->handle, AV_VIDEO_TRICK_MODE_NONE);
     }
-    AmTsPlayer_setVideoParams(player->handle, &vparams);
+    AmTsPlayer_setVideoParams(player->handle, &video_params);
     AmTsPlayer_setVideoBlackOut(player->handle, 1);
     AmTsPlayer_startVideoDecoding(player->handle);
   }
 
   if (IS_FAST_SPEED(player->cmd.speed.speed.speed)) {
-    DVR_PB_DG(1, "start fast");
+    DVR_PB_INFO("start fast");
     AmTsPlayer_startFast(player->handle, (float)player->cmd.speed.speed.speed/(float)100);
     player->speed = (float)player->cmd.speed.speed.speed/100.0f;
   } else {
-    if (VALID_PID(adparams.pid)) {
+    if (VALID_PID(ad_params.pid)) {
       player->has_ad_audio = DVR_TRUE;
-      DVR_PB_DG(1, "start ad audio");
-      AmTsPlayer_setADParams(player->handle,  &adparams);
+      DVR_PB_INFO("start ad audio");
+      AmTsPlayer_setADParams(player->handle,  &ad_params);
       AmTsPlayer_enableADMix(player->handle);
     }
-    if (VALID_PID(aparams.pid)) {
+    if (VALID_PID(audio_params.pid)) {
       player->has_audio = DVR_TRUE;
-      DVR_PB_DG(1, "start audio");
-      AmTsPlayer_setAudioParams(player->handle, &aparams);
+      DVR_PB_INFO("start audio");
+      AmTsPlayer_setAudioParams(player->handle, &audio_params);
+      if (player->audio_presentation_id > -1) {
+        AmTsPlayer_setParams(player->handle, AM_TSPLAYER_KEY_AUDIO_PRESENTATION_ID, &player->audio_presentation_id);
+      }
       AmTsPlayer_startAudioDecoding(player->handle);
     }
 
-    DVR_PB_DG(1, "stop fast");
+    DVR_PB_INFO("stop fast");
     AmTsPlayer_stopFast(player->handle);
     player->cmd.speed.speed.speed = PLAYBACK_SPEED_X1;
     player->speed = (float)PLAYBACK_SPEED_X1/100.0f;
   }
+#ifdef AVSYNC_USED_PCR
+  if (player && VALID_PID(player->cur_segment.pids.pcr.pid)) {
+    DVR_PB_INFO("start set pcr [%d]", player->cur_segment.pids.pcr.pid);
+    AmTsPlayer_setPcrPid(player->handle, player->cur_segment.pids.pcr.pid);
+  }
+#endif
   player->cmd.last_cmd = player->cmd.cur_cmd;
   player->cmd.cur_cmd = DVR_PLAYBACK_CMD_START;
   player->cmd.state = DVR_PLAYBACK_STATE_START;
-  player->state = DVR_PLAYBACK_STATE_START;
+  DVR_PLAYER_CHANGE_STATE(player,DVR_PLAYBACK_STATE_START);
   return 0;
 }
 
@@ -3573,21 +3795,21 @@
   DVR_Playback_t *player = (DVR_Playback_t *) handle;
 
   if (player == NULL) {
-    DVR_PB_DG(1, "player is NULL");
+    DVR_PB_INFO("player is NULL");
     return DVR_FAILURE;
   }
 
   if (_dvr_support_speed(speed.speed.speed) == DVR_FALSE) {
-    DVR_PB_DG(1, " func: not support speed [%d]", speed.speed.speed);
+    DVR_PB_INFO(" func: not support speed [%d]", speed.speed.speed);
     return DVR_FAILURE;
   }
   if (speed.speed.speed == player->cmd.speed.speed.speed) {
-    DVR_PB_DG(1, " func: eq speed [%d]", speed.speed.speed);
+    DVR_PB_INFO(" func: eq speed [%d]", speed.speed.speed);
     return DVR_SUCCESS;
   }
-  DVR_PB_DG(1, "lock func: speed [%d]", speed.speed.speed);
+  DVR_PB_INFO("lock func: speed [%d]", speed.speed.speed);
 
-  pthread_mutex_lock(&player->lock);
+  dvr_mutex_lock(&player->lock);
   if (player->cmd.cur_cmd != DVR_PLAYBACK_CMD_FF
     && player->cmd.cur_cmd != DVR_PLAYBACK_CMD_FB) {
     player->cmd.last_cmd = player->cmd.cur_cmd;
@@ -3602,8 +3824,8 @@
         player->cmd.speed.speed = speed.speed;
         player->speed = (float)speed.speed.speed/(float)100;
         player->fffb_play = DVR_FALSE;
-        pthread_mutex_unlock(&player->lock);
-        DVR_PB_DG(1, "unlock");
+        dvr_mutex_unlock(&player->lock);
+        DVR_PB_DEBUG("unlock");
         return DVR_SUCCESS;
       }
      //case 2. cur speed is 100,set 200 50 25 12 .
@@ -3612,43 +3834,43 @@
       //if last speed is x2 or s2, we need stop fast
       if (speed.speed.speed == PLAYBACK_SPEED_X1) {
         // resume audio and stop fast play
-        DVR_PB_DG(1, "stop fast");
+        DVR_PB_INFO("stop fast");
         AmTsPlayer_stopFast(player->handle);
-        pthread_mutex_unlock(&player->lock);
-        DVR_PB_DG(1, "unlock ---\r\n");
-        _dvr_cmd(handle, DVR_PLAYBACK_CMD_ASTART);
-        DVR_PB_DG(1, "lock ---\r\n");
-        pthread_mutex_lock(&player->lock);
+        dvr_mutex_unlock(&player->lock);
+        DVR_PB_DEBUG("unlock ---\r\n");
+        _dvr_cmd(handle, DVR_PLAYBACK_CMD_A_START);
+        DVR_PB_DEBUG("lock ---\r\n");
+        dvr_mutex_lock(&player->lock);
       } else {
         //set play speed and if audio is start, stop audio.
         if (player->has_audio) {
-          DVR_PB_DG(1, "fast play stop audio");
+          DVR_PB_INFO("fast play stop audio");
           AmTsPlayer_stopAudioDecoding(player->handle);
           player->has_audio = DVR_FALSE;
         }
-        DVR_PB_DG(1, "start fast");
+        DVR_PB_INFO("start fast");
         AmTsPlayer_startFast(player->handle, (float)speed.speed.speed/(float)100);
       }
       player->fffb_play = DVR_FALSE;
       player->cmd.speed.mode = DVR_PLAYBACK_KERNEL_SUPPORT;
       player->cmd.speed.speed = speed.speed;
       player->speed = (float)speed.speed.speed/(float)100;
-      DVR_PB_DG(1, "unlock ---\r\n");
-      pthread_mutex_unlock(&player->lock);
+      DVR_PB_DEBUG("unlock ---\r\n");
+      dvr_mutex_unlock(&player->lock);
       return DVR_SUCCESS;
      }
     //case 3 fffb mode
     if (player->cmd.cur_cmd == DVR_PLAYBACK_CMD_FF ||
       player->cmd.cur_cmd == DVR_PLAYBACK_CMD_FB) {
       //restart play at normal speed exit ff fb
-      DVR_PB_DG(1, "set speed normal and replay playback");
+      DVR_PB_INFO("set speed normal and replay playback");
       player->cmd.speed.mode = DVR_PLAYBACK_KERNEL_SUPPORT;
       player->cmd.speed.speed = speed.speed;
       player->speed = (float)speed.speed.speed/(float)100;
       _dvr_playback_replay(handle, DVR_FALSE);
       player->fffb_play = DVR_FALSE;
-      DVR_PB_DG(1, "unlock ---\r\n");
-      pthread_mutex_unlock(&player->lock);
+      DVR_PB_DEBUG("unlock ---\r\n");
+      dvr_mutex_unlock(&player->lock);
       return DVR_SUCCESS;
     }
   }
@@ -3659,39 +3881,39 @@
      //if last speed is x2 or s2, we need stop fast
      if (speed.speed.speed == PLAYBACK_SPEED_X1) {
         // resume audio and stop fast play
-        DVR_PB_DG(1, "stop fast");
+        DVR_PB_INFO("stop fast");
         AmTsPlayer_stopFast(player->handle);
-        player->cmd.cur_cmd = DVR_PLAYBACK_CMD_ASTART;
+        player->cmd.cur_cmd = DVR_PLAYBACK_CMD_A_START;
       } else {
         //set play speed and if audio is start, stop audio.
         if (player->has_audio) {
-          DVR_PB_DG(1, "fast play stop audio at pause");
+          DVR_PB_INFO("fast play stop audio at pause");
           AmTsPlayer_stopAudioDecoding(player->handle);
           player->has_audio = DVR_FALSE;
        }
-       DVR_PB_DG(1, "start fast");
+       DVR_PB_INFO("start fast");
        AmTsPlayer_startFast(player->handle, (float)speed.speed.speed/(float)100);
      }
      player->cmd.speed.mode = DVR_PLAYBACK_KERNEL_SUPPORT;
      player->cmd.speed.speed = speed.speed;
      player->speed = (float)speed.speed.speed/(float)100;
      player->fffb_play = DVR_FALSE;
-     DVR_PB_DG(1, "unlock ---\r\n");
-     pthread_mutex_unlock(&player->lock);
+     DVR_PB_DEBUG("unlock ---\r\n");
+     dvr_mutex_unlock(&player->lock);
      return DVR_SUCCESS;
     }
     //case 2 fffb mode
     if (player->cmd.cur_cmd == DVR_PLAYBACK_CMD_FF ||
       player->cmd.cur_cmd == DVR_PLAYBACK_CMD_FB) {
       //restart play at normal speed exit ff fb
-      DVR_PB_DG(1, "set speed x1 s2 and replay playback");
+      DVR_PB_INFO("set speed x1 s2 and replay playback");
       player->cmd.speed.mode = DVR_PLAYBACK_KERNEL_SUPPORT;
       player->cmd.speed.speed = speed.speed;
       player->speed = (float)speed.speed.speed/(float)100;
-      player->cmd.cur_cmd = DVR_PLAYBACK_CMD_AVRESTART;
+      player->cmd.cur_cmd = DVR_PLAYBACK_CMD_AV_RESTART;
       player->fffb_play = DVR_FALSE;
-      DVR_PB_DG(1, "unlock ---\r\n");
-      pthread_mutex_unlock(&player->lock);
+      DVR_PB_DEBUG("unlock ---\r\n");
+      dvr_mutex_unlock(&player->lock);
       return DVR_SUCCESS;
     }
   }
@@ -3723,15 +3945,15 @@
     (player->cmd.cur_cmd == DVR_PLAYBACK_CMD_FF ||
     player->cmd.cur_cmd == DVR_PLAYBACK_CMD_FB)) {
     //restart play at normal speed exit ff fb
-    DVR_PB_DG(1, "set speed normal and replay playback");
+    DVR_PB_INFO("set speed normal and replay playback");
     _dvr_playback_replay(handle, DVR_FALSE);
   } else if (speed.speed.speed == PLAYBACK_SPEED_X1 &&
     (player->state == DVR_PLAYBACK_STATE_PAUSE)) {
-    player->cmd.cur_cmd = DVR_PLAYBACK_CMD_AVRESTART;
-    DVR_PB_DG(1, "set speed normal at pause state ,set cur cmd");
+    player->cmd.cur_cmd = DVR_PLAYBACK_CMD_AV_RESTART;
+    DVR_PB_INFO("set speed normal at pause state ,set cur cmd");
   }
-  DVR_PB_DG(1, "unlock  speed[%f]cmd[%d]", player->speed, player->cmd.cur_cmd);
-  pthread_mutex_unlock(&player->lock);
+  DVR_PB_INFO("unlock  speed[%f]cmd[%d]", player->speed, player->cmd.cur_cmd);
+  dvr_mutex_unlock(&player->lock);
   return DVR_SUCCESS;
 }
 
@@ -3747,12 +3969,12 @@
   DVR_Playback_t *player = (DVR_Playback_t *) handle;
   uint64_t   segment_id = 0LL;
   if (player == NULL) {
-    DVR_PB_DG(1, "player is NULL");
+    DVR_PB_INFO("player is NULL");
     return DVR_FAILURE;
   }
   if (is_lock ==DVR_TRUE) {
-    DVR_PB_DG(1, "lock");
-    pthread_mutex_lock(&player->lock);
+    DVR_PB_DEBUG("lock");
+    dvr_mutex_lock(&player->lock);
   }
 
   p_status->state = player->state;
@@ -3767,14 +3989,14 @@
 
   if (CONTROL_SPEED_ENABLE == 1) {
     if (player->con_spe.ply_sta == 0) {
-          DVR_PB_DG(1, "player dur[%u] sta[%u] cur[%d] -----reinit",
+          DVR_PB_INFO("player dur[%u] sta[%u] cur[%d] -----reinit",
                         player->con_spe.ply_dur,
                         player->con_spe.ply_sta,
                         p_status->time_cur);
           player->con_spe.ply_sta = p_status->time_cur;
       } else if (player->speed == 1.0f && player->con_spe.ply_sta < p_status->time_cur) {
         player->con_spe.ply_dur += (p_status->time_cur - player->con_spe.ply_sta);
-        DVR_PB_DG(1, "player dur[%u] sta[%u] cur[%d]",
+        DVR_PB_INFO("player dur[%u] sta[%u] cur[%d]",
                       player->con_spe.ply_dur,
                       player->con_spe.ply_sta,
                       p_status->time_cur);
@@ -3794,10 +4016,10 @@
     player->last_cur_time = p_status->time_cur;
   }
   if (player->last_send_time_id == player->cur_segment_id) {
-    if (player->speed > 0.0f ) {
+    if (player->speed > 1.0f ) {
       //ff
       if (p_status->time_cur < player->last_cur_time ) {
-        DVR_PB_DG(1, "get ff time error last[%d]cur[%d]diff[%d]",
+        DVR_PB_INFO("get ff time error last[%d]cur[%d]diff[%d]",
                       player->last_cur_time,
                       p_status->time_cur,
                       player->last_cur_time - p_status->time_cur);
@@ -3808,7 +4030,7 @@
     } else if (player->speed <= -1.0f){
       //fb
       if (p_status->time_cur > player->last_cur_time ) {
-        DVR_PB_DG(1, "get fb time error last[%d]cur[%d]diff[%d]",
+        DVR_PB_INFO("get fb time error last[%d]cur[%d]diff[%d]",
                       player->last_cur_time,
                       p_status->time_cur,
                       p_status->time_cur - player->last_cur_time );
@@ -3826,7 +4048,7 @@
   memcpy(&p_status->pids, &player->cur_segment.pids, sizeof(DVR_PlaybackPids_t));
   p_status->speed = player->cmd.speed.speed.speed;
   p_status->flags = player->cur_segment.flags;
-  DVR_PB_DG(1, "player real state[%s]state[%s]cur[%d]end[%d] id[%lld]playflag[%d]speed[%f]is_lock[%d]",
+  DVR_PB_INFO("player real state[%s]state[%s]cur[%d]end[%d] id[%lld]playflag[%d]speed[%f]is_lock[%d]",
                 _dvr_playback_state_toString(player->state),
                 _dvr_playback_state_toString(p_status->state),
                 p_status->time_cur, p_status->time_end,
@@ -3834,8 +4056,8 @@
                 player->speed,
                 is_lock);
   if (is_lock ==DVR_TRUE) {
-    DVR_PB_DG(1, "unlock ---\r\n");
-    pthread_mutex_unlock(&player->lock);
+    DVR_PB_DEBUG("unlock ---\r\n");
+    dvr_mutex_unlock(&player->lock);
   }
   return DVR_SUCCESS;
 }
@@ -3855,28 +4077,28 @@
   _dvr_playback_get_status(handle, p_status, DVR_TRUE);
 
   if (player == NULL) {
-    DVR_PB_DG(1, "player is NULL");
+    DVR_PB_INFO("player is NULL");
     return DVR_FAILURE;
   }
-  DVR_PB_DG(1, "lock---");
-  pthread_mutex_lock(&player->lock);
+  DVR_PB_DEBUG("lock---");
+  dvr_mutex_lock(&player->lock);
   if (!player->has_video && !player->has_audio)
     p_status->time_cur = 0;
-  DVR_PB_DG(1, "unlock---");
-  pthread_mutex_unlock(&player->lock);
+  DVR_PB_DEBUG("unlock---");
+  dvr_mutex_unlock(&player->lock);
 
   return DVR_SUCCESS;
 }
 
 void _dvr_dump_segment(DVR_PlaybackSegmentInfo_t *segment) {
   if (segment != NULL) {
-    DVR_PB_DG(1, "segment id: %lld", segment->segment_id);
-    DVR_PB_DG(1, "segment flag: %d", segment->flags);
-    DVR_PB_DG(1, "segment location: [%s]", segment->location);
-    DVR_PB_DG(1, "segment vpid: 0x%x vfmt:0x%x", segment->pids.video.pid,segment->pids.video.format);
-    DVR_PB_DG(1, "segment apid: 0x%x afmt:0x%x", segment->pids.audio.pid,segment->pids.audio.format);
-    DVR_PB_DG(1, "segment pcr pid: 0x%x pcr fmt:0x%x", segment->pids.pcr.pid,segment->pids.pcr.format);
-    DVR_PB_DG(1, "segment sub apid: 0x%x sub afmt:0x%x", segment->pids.ad.pid,segment->pids.ad.format);
+    DVR_PB_INFO("segment id: %lld", segment->segment_id);
+    DVR_PB_INFO("segment flag: %d", segment->flags);
+    DVR_PB_INFO("segment location: [%s]", segment->location);
+    DVR_PB_INFO("segment vpid: 0x%x vfmt:0x%x", segment->pids.video.pid,segment->pids.video.format);
+    DVR_PB_INFO("segment apid: 0x%x afmt:0x%x", segment->pids.audio.pid,segment->pids.audio.format);
+    DVR_PB_INFO("segment pcr pid: 0x%x pcr fmt:0x%x", segment->pids.pcr.pid,segment->pids.pcr.format);
+    DVR_PB_INFO("segment sub apid: 0x%x sub afmt:0x%x", segment->pids.ad.pid,segment->pids.ad.format);
   }
 }
 
@@ -3884,21 +4106,20 @@
   DVR_Playback_t *player = (DVR_Playback_t *) handle;
 
   if (player == NULL) {
-    DVR_PB_DG(1, "player is NULL");
+    DVR_PB_INFO("player is NULL");
     return DVR_FAILURE;
   }
 
   DVR_PlaybackSegmentInfo_t *segment;
+  // This error is suppressed as the macro code is picked from kernel.
+  // prefetch() here incurring self_assign is used to avoid some compiling
+  // warnings.
+  // coverity[self_assign]
   list_for_each_entry(segment, &player->segment_list, head)
   {
-    if (segment_id >= 0) {
-      if (segment->segment_id == segment_id) {
-        _dvr_dump_segment(segment);
-       break;
-      }
-    } else {
-      //printf segment info
+    if (segment->segment_id == segment_id) {
       _dvr_dump_segment(segment);
+      break;
     }
   }
   return 0;
@@ -3910,14 +4131,14 @@
   DVR_RETURN_IF_FALSE(player);
   DVR_RETURN_IF_FALSE(func);
 
-  DVR_PB_DG(1, "in ");
-  pthread_mutex_lock(&player->lock);
+  DVR_PB_INFO("in ");
+  dvr_mutex_lock(&player->lock);
 
   player->dec_func = func;
   player->dec_userdata = userdata;
 
-  pthread_mutex_unlock(&player->lock);
-  DVR_PB_DG(1, "out ");
+  dvr_mutex_unlock(&player->lock);
+  DVR_PB_INFO("out ");
   return DVR_SUCCESS;
 }
 
@@ -3928,14 +4149,27 @@
   DVR_RETURN_IF_FALSE(p_secure_buf);
   DVR_RETURN_IF_FALSE(len);
 
-  DVR_PB_DG(1, "in ");
-  pthread_mutex_lock(&player->lock);
+  DVR_PB_INFO("in ");
+  dvr_mutex_lock(&player->lock);
 
   player->is_secure_mode = 1;
   player->secure_buffer = p_secure_buf;
   player->secure_buffer_size = len;
 
-  pthread_mutex_unlock(&player->lock);
-  DVR_PB_DG(1, "out");
+  dvr_mutex_unlock(&player->lock);
+  DVR_PB_INFO("out");
+  return DVR_SUCCESS;
+}
+
+int dvr_playback_set_ac4_preselection_id(DVR_PlaybackHandle_t handle, int presel_id)
+{
+  DVR_Playback_t *player = (DVR_Playback_t *) handle;
+  DVR_RETURN_IF_FALSE(player != NULL);
+
+  player->audio_presentation_id = presel_id;
+  am_tsplayer_result ret = AmTsPlayer_setParams(player->handle,
+      AM_TSPLAYER_KEY_AUDIO_PRESENTATION_ID, &presel_id);
+  DVR_RETURN_IF_FALSE(ret == AM_TSPLAYER_OK);
+
   return DVR_SUCCESS;
 }
diff --git a/src/dvr_record.c b/src/dvr_record.c
index b381aae..5d4eada 100644
--- a/src/dvr_record.c
+++ b/src/dvr_record.c
@@ -14,6 +14,8 @@
 
 #define CONTROL_SPEED_ENABLE 0
 
+#define CHECK_PTS_MAX_COUNT  (20)
+
 //#define DEBUG_PERFORMANCE
 #define MAX_DVR_RECORD_SESSION_COUNT 4
 #define RECORD_BLOCK_SIZE (256 * 1024)
@@ -57,7 +59,7 @@
   char                            location[DVR_MAX_LOCATION_SIZE];      /**< DVR record file location*/
   DVR_RecordSegmentStartParams_t  segment_params;                       /**< DVR record start parameters*/
   DVR_RecordSegmentInfo_t         segment_info;                         /**< DVR record current segment info*/
-  size_t                          notification_size;                    /**< DVR record nogification size*/
+  size_t                          notification_size;                    /**< DVR record notification size*/
   DVR_RecordEventFunction_t       event_notify_fn;                      /**< DVR record event notify function*/
   void                            *event_userdata;                      /**< DVR record event userdata*/
   //DVR_VodContext_t                vod;                                  /**< DVR record vod context*/
@@ -70,6 +72,15 @@
   uint32_t                        block_size;                           /**< DVR record block size */
   DVR_Bool_t                      is_new_dmx;                           /**< DVR is used new dmx driver */
   int                             index_type;                           /**< DVR is used pcr or local time */
+  DVR_Bool_t                      force_sysclock;                       /**< If ture, force to use system clock as PVR index time source. If false, libdvr can determine index time source based on actual situation*/
+  uint64_t                        pts;                                  /**< The newest pcr or local time */
+  int                             check_pts_count;                      /**< The check count of pts */
+  int                             check_no_pts_count;                   /**< The check count of no pts */
+  int                             notification_time;                    /**< DVR record notification time*/
+  time_t                          last_send_time;                       /**< Last send notify segment duration */
+  loff_t                          guarded_segment_size;                 /**< Guarded segment size in bytes. Libdvr will be forcely stopped to write anymore if current segment reaches this size*/
+  size_t                          secbuf_size;                          /**< DVR record secure buffer length*/
+  DVR_Bool_t                      discard_coming_data;                  /**< Whether to discard subsequent recording data due to exceeding total size limit too much.*/
 } DVR_RecordContext_t;
 
 extern ssize_t record_device_read_ext(Record_DeviceHandle_t handle, size_t *buf, size_t *len);
@@ -131,16 +142,21 @@
       has_pcr = 1;
     }
 
-    p += adp_field_len;
     len -= adp_field_len;
 
     if (len < 0) {
-      DVR_DEBUG(1, "parser pcr: illegal adaptation field length");
+      DVR_INFO("parser pcr: illegal adaptation field length");
       return 0;
     }
   }
 
   if (has_pcr && p_ctx->index_type == DVR_INDEX_TYPE_PCR) {
+    //save newest pcr
+    if (p_ctx->pts == pcr/90 &&
+      p_ctx->check_pts_count < CHECK_PTS_MAX_COUNT) {
+      p_ctx->check_pts_count ++;
+    }
+    p_ctx->pts = pcr/90;
     segment_update_pts(p_ctx->segment_handle, pcr/90, pos);
   }
   return has_pcr;
@@ -154,7 +170,9 @@
   int has_pcr = 0;
 
   pos = segment_tell_position(p_ctx->segment_handle);
-
+  if (pos >= len) {
+    pos = pos - len;
+  }
   while (left >= 188) {
     if (*p == 0x47) {
       has_pcr |= record_save_pcr(p_ctx, p, pos);
@@ -182,14 +200,16 @@
   uint8_t *buf, *buf_out;
   uint32_t block_size = p_ctx->block_size;
   loff_t pos = 0;
-  int ret;
-  struct timespec start_ts, end_ts;
+  int ret = DVR_SUCCESS;
+  struct timespec start_ts, end_ts, start_no_pcr_ts, end_no_pcr_ts;
   DVR_RecordStatus_t record_status;
   int has_pcr;
+  int pcr_rec_len = 0;
+  DVR_Bool_t guarded_size_exceeded = DVR_FALSE;
 
   time_t pre_time = 0;
   #define DVR_STORE_INFO_TIME (400)
-  DVR_SecureBuffer_t secure_buf;
+  DVR_SecureBuffer_t secure_buf = {0,0};
   DVR_NewDmxSecureBuffer_t new_dmx_secure_buf;
   int first_read = 0;
   if (CONTROL_SPEED_ENABLE == 0)
@@ -197,15 +217,23 @@
   else
     p_ctx->index_type = DVR_INDEX_TYPE_LOCAL_CLOCK;
 
+  // Force to use LOCAL_CLOCK as index type if force_sysclock is on. Please
+  // refer to SWPL-75327
+  if (p_ctx->force_sysclock)
+    p_ctx->index_type = DVR_INDEX_TYPE_LOCAL_CLOCK;
   buf = (uint8_t *)malloc(block_size);
   if (!buf) {
-    DVR_DEBUG(1, "%s, malloc failed", __func__);
+    DVR_INFO("%s, malloc failed", __func__);
     return NULL;
   }
 
-  buf_out = (uint8_t *)malloc(block_size + 188);
+  if (p_ctx->is_secure_mode) {
+    buf_out = (uint8_t *)malloc(p_ctx->secbuf_size + 188);
+  } else {
+    buf_out = (uint8_t *)malloc(block_size + 188);
+  }
   if (!buf_out) {
-    DVR_DEBUG(1, "%s, malloc failed", __func__);
+    DVR_INFO("%s, malloc failed", __func__);
     free(buf);
     return NULL;
   }
@@ -215,14 +243,17 @@
   if (p_ctx->event_notify_fn) {
     record_status.info.id = p_ctx->segment_info.id;
     p_ctx->event_notify_fn(DVR_RECORD_EVENT_STATUS, &record_status, p_ctx->event_userdata);
-    DVR_DEBUG(1, "%s line %d notify record status, state:%d id=%lld",
+    DVR_INFO("%s line %d notify record status, state:%d id=%lld",
           __func__,__LINE__, record_status.state, p_ctx->segment_info.id);
   }
-  DVR_DEBUG(1, "%s, secure_mode:%d, block_size:%d, cryptor:%p",
-	    __func__, p_ctx->is_secure_mode,
-	    block_size, p_ctx->cryptor);
+  DVR_INFO("%s, --secure_mode:%d, block_size:%d, cryptor:%p",
+        __func__, p_ctx->is_secure_mode,
+        block_size, p_ctx->cryptor);
   clock_gettime(CLOCK_MONOTONIC, &start_ts);
-
+  p_ctx->check_pts_count = 0;
+  p_ctx->check_no_pts_count++;
+  p_ctx->last_send_size = 0;
+  p_ctx->last_send_time = 0;
   struct timeval t1, t2, t3, t4, t5, t6, t7;
   while (p_ctx->state == DVR_RECORD_STATE_STARTED ||
     p_ctx->state == DVR_RECORD_STATE_PAUSE) {
@@ -241,39 +272,52 @@
           /* We resolve the below invoke for dvbcore to be under safety status */
           memset(&new_dmx_secure_buf, 0, sizeof(new_dmx_secure_buf));
           len = record_device_read(p_ctx->dev_handle, &new_dmx_secure_buf, sizeof(new_dmx_secure_buf), 10);
-	  if (len == DVR_FAILURE) {
-	    DVR_DEBUG(1, "handle[%p] ret:%d\n", p_ctx->dev_handle, ret);
-	    /*For the second recording, poll always failed which we should check
-	     * dvbcore further. For now, Just ignore the fack poll fail, I think
-	     * it won't influce anything. But we need adjust the poll timeout
-	     * from 1000ms to 10ms.
-	     */
-	    //continue;
-	  }
+      if (len == DVR_FAILURE) {
+        DVR_INFO("handle[%p] ret:%d\n", p_ctx->dev_handle, ret);
+        /*For the second recording, poll always failed which we should check
+         * dvbcore further. For now, Just ignore the fack poll fail, I think
+         * it won't influence anything. But we need adjust the poll timeout
+         * from 1000ms to 10ms.
+         */
+        //continue;
+      }
 
-	  /* Read data from secure demux TA */
-	  len = record_device_read_ext(p_ctx->dev_handle, &secure_buf.addr,
-				       &secure_buf.len);
+      /* Read data from secure demux TA */
+      len = record_device_read_ext(p_ctx->dev_handle, &secure_buf.addr,
+                       &secure_buf.len);
 
       } else {
           memset(&secure_buf, 0, sizeof(secure_buf));
           len = record_device_read(p_ctx->dev_handle, &secure_buf, sizeof(secure_buf), 1000);
       }
       if (len != DVR_FAILURE) {
-        //DVR_DEBUG(1, "%s, secure_buf:%#x, size:%#x", __func__, secure_buf.addr, secure_buf.len);
+        //DVR_INFO("%s, secure_buf:%#x, size:%#x", __func__, secure_buf.addr, secure_buf.len);
       }
     } else {
       len = record_device_read(p_ctx->dev_handle, buf, block_size, 1000);
     }
     if (len == DVR_FAILURE) {
       //usleep(10*1000);
-      DVR_DEBUG(1, "%s, start_read error", __func__);
+      //DVR_INFO("%s, start_read error", __func__);
       continue;
     }
     gettimeofday(&t2, NULL);
 
+    guarded_size_exceeded = DVR_FALSE;
+    if (p_ctx->segment_info.size+len >= p_ctx->guarded_segment_size) {
+      guarded_size_exceeded = DVR_TRUE;
+    }
     /* Got data from device, record it */
-    if (p_ctx->is_secure_mode && p_ctx->enc_func) {
+    if (guarded_size_exceeded) {
+      len = 0;
+      ret = 0;
+      DVR_ERROR("Skip segment_write due to current segment size %u exceeding"
+        " guarded segment size", p_ctx->segment_info.size);
+    } else if (p_ctx->discard_coming_data) {
+      len = 0;
+      ret = 0;
+      DVR_ERROR("Skip segment_write due to total size exceeding max size too much");
+    } else if (p_ctx->enc_func) {
       /* Encrypt record data */
       DVR_CryptoParams_t crypto_params;
 
@@ -287,15 +331,16 @@
         crypto_params.input_buffer.type = DVR_BUFFER_TYPE_SECURE;
         crypto_params.input_buffer.addr = secure_buf.addr;
         crypto_params.input_buffer.size = secure_buf.len;
+        crypto_params.output_buffer.size = p_ctx->secbuf_size + 188;
       } else {
         crypto_params.input_buffer.type = DVR_BUFFER_TYPE_NORMAL;
         crypto_params.input_buffer.addr = (size_t)buf;
         crypto_params.input_buffer.size = len;
+        crypto_params.output_buffer.size = block_size + 188;
       }
 
       crypto_params.output_buffer.type = DVR_BUFFER_TYPE_NORMAL;
       crypto_params.output_buffer.addr = (size_t)buf_out;
-      crypto_params.output_buffer.size = block_size + 188;
 
       p_ctx->enc_func(&crypto_params, p_ctx->enc_userdata);
       gettimeofday(&t3, NULL);
@@ -308,13 +353,15 @@
       }
     } else if (p_ctx->cryptor) {
       /* Encrypt with clear key */
-      am_crypt_des_crypt(p_ctx->cryptor, buf_out, buf, (uint32_t *)&len, 0);
+      int crypt_len = len;
+      am_crypt_des_crypt(p_ctx->cryptor, buf_out, buf, &crypt_len, 0);
+      len = crypt_len;
       gettimeofday(&t3, NULL);
       ret = segment_write(p_ctx->segment_handle, buf_out, len);
     } else {
       if (first_read == 0) {
         first_read = 1;
-        DVR_DEBUG(1, "%s:%d,first read ts", __func__,__LINE__);
+        DVR_INFO("%s:%d,first read ts", __func__,__LINE__);
       }
       gettimeofday(&t3, NULL);
       ret = segment_write(p_ctx->segment_handle, buf, len);
@@ -325,87 +372,145 @@
       //send write event
        if (p_ctx->event_notify_fn) {
          memset(&record_status, 0, sizeof(record_status));
-         DVR_DEBUG(1, "%s:%d,send event write error", __func__,__LINE__);
+         DVR_INFO("%s:%d,send event write error", __func__,__LINE__);
          record_status.info.id = p_ctx->segment_info.id;
          p_ctx->event_notify_fn(DVR_RECORD_EVENT_WRITE_ERROR, &record_status, p_ctx->event_userdata);
         }
-        DVR_DEBUG(1, "%s,write error %d", __func__,__LINE__);
+        DVR_INFO("%s,write error %d", __func__,__LINE__);
       goto end;
     }
-    /* Do time index */
-    uint8_t *index_buf = (p_ctx->enc_func || p_ctx->cryptor)? buf_out : buf;
-    pos = segment_tell_position(p_ctx->segment_handle);
-    has_pcr = record_do_pcr_index(p_ctx, index_buf, len);
-    if (has_pcr == 0 && p_ctx->index_type == DVR_INDEX_TYPE_INVALID) {
-      clock_gettime(CLOCK_MONOTONIC, &end_ts);
-      if ((end_ts.tv_sec*1000 + end_ts.tv_nsec/1000000) -
-          (start_ts.tv_sec*1000 + start_ts.tv_nsec/1000000) > 40) {
-        /* PCR interval threshlod > 40 ms*/
-        DVR_DEBUG(1, "%s use local clock time index", __func__);
-        p_ctx->index_type = DVR_INDEX_TYPE_LOCAL_CLOCK;
+    if (len>0) {
+      /* Do time index */
+      uint8_t *index_buf = (p_ctx->enc_func || p_ctx->cryptor)? buf_out : buf;
+      pos = segment_tell_position(p_ctx->segment_handle);
+      has_pcr = record_do_pcr_index(p_ctx, index_buf, len);
+      if (has_pcr == 0 && p_ctx->index_type == DVR_INDEX_TYPE_INVALID) {
+        clock_gettime(CLOCK_MONOTONIC, &end_ts);
+        if ((end_ts.tv_sec*1000 + end_ts.tv_nsec/1000000) -
+            (start_ts.tv_sec*1000 + start_ts.tv_nsec/1000000) > 40) {
+          /* PCR interval threshold > 40 ms*/
+          DVR_INFO("%s use local clock time index", __func__);
+          p_ctx->index_type = DVR_INDEX_TYPE_LOCAL_CLOCK;
+        }
+      } else if (has_pcr && p_ctx->index_type == DVR_INDEX_TYPE_INVALID){
+        DVR_INFO("%s use pcr time index", __func__);
+        p_ctx->index_type = DVR_INDEX_TYPE_PCR;
+        record_do_pcr_index(p_ctx, index_buf, len);
       }
-    } else if (has_pcr && p_ctx->index_type == DVR_INDEX_TYPE_INVALID){
-      DVR_DEBUG(1, "%s use pcr time index", __func__);
-      p_ctx->index_type = DVR_INDEX_TYPE_PCR;
-    }
-    gettimeofday(&t5, NULL);
+      gettimeofday(&t5, NULL);
+      if (p_ctx->index_type == DVR_INDEX_TYPE_PCR) {
+        if (has_pcr == 0) {
+          if (p_ctx->check_no_pts_count < 2 * CHECK_PTS_MAX_COUNT) {
+            if (p_ctx->check_no_pts_count == 0) {
+              clock_gettime(CLOCK_MONOTONIC, &start_no_pcr_ts);
+              clock_gettime(CLOCK_MONOTONIC, &start_ts);
+            }
+            p_ctx->check_no_pts_count++;
+          }
+        } else {
+          clock_gettime(CLOCK_MONOTONIC, &start_no_pcr_ts);
+          p_ctx->check_no_pts_count = 0;
+        }
+      }
+      /* Update segment i nfo */
+      p_ctx->segment_info.size += len;
 
-    /* Update segment info */
-    p_ctx->segment_info.size += len;
-    /*Duration need use pcr to calculate, todo...*/
-    if (p_ctx->index_type == DVR_INDEX_TYPE_PCR) {
-      p_ctx->segment_info.duration = segment_tell_total_time(p_ctx->segment_handle);
-      if (pre_time == 0)
-       pre_time = p_ctx->segment_info.duration;
-    } else if (p_ctx->index_type == DVR_INDEX_TYPE_LOCAL_CLOCK) {
-      clock_gettime(CLOCK_MONOTONIC, &end_ts);
-      p_ctx->segment_info.duration = (end_ts.tv_sec*1000 + end_ts.tv_nsec/1000000) -
-        (start_ts.tv_sec*1000 + start_ts.tv_nsec/1000000);
-            if (pre_time == 0)
-       pre_time = p_ctx->segment_info.duration;
-      segment_update_pts(p_ctx->segment_handle, p_ctx->segment_info.duration, pos);
+      /*Duration need use pcr to calculate, todo...*/
+      if (p_ctx->index_type == DVR_INDEX_TYPE_PCR) {
+        p_ctx->segment_info.duration = segment_tell_total_time(p_ctx->segment_handle);
+        if (pre_time == 0)
+         pre_time = p_ctx->segment_info.duration;
+      } else if (p_ctx->index_type == DVR_INDEX_TYPE_LOCAL_CLOCK) {
+        clock_gettime(CLOCK_MONOTONIC, &end_ts);
+        p_ctx->segment_info.duration = (end_ts.tv_sec*1000 + end_ts.tv_nsec/1000000) -
+          (start_ts.tv_sec*1000 + start_ts.tv_nsec/1000000) + pcr_rec_len;
+        if (pre_time == 0)
+          pre_time = p_ctx->segment_info.duration;
+        segment_update_pts(p_ctx->segment_handle, p_ctx->segment_info.duration, pos);
+      } else {
+        DVR_INFO("%s can NOT do time index", __func__);
+      }
+      if (p_ctx->index_type == DVR_INDEX_TYPE_PCR &&
+          p_ctx->check_pts_count == CHECK_PTS_MAX_COUNT) {
+         DVR_INFO("%s change time from pcr to local time", __func__);
+         if (pcr_rec_len == 0)
+              pcr_rec_len = segment_tell_total_time(p_ctx->segment_handle);
+         p_ctx->index_type = DVR_INDEX_TYPE_LOCAL_CLOCK;
+        if (pcr_rec_len == 0)
+              pcr_rec_len = segment_tell_total_time(p_ctx->segment_handle);
+         clock_gettime(CLOCK_MONOTONIC, &start_ts);
+      }
+
+      if (p_ctx->index_type == DVR_INDEX_TYPE_PCR ) {
+         clock_gettime(CLOCK_MONOTONIC, &end_no_pcr_ts);
+         int diff = (int)(end_no_pcr_ts.tv_sec*1000 + end_no_pcr_ts.tv_nsec/1000000) -
+          (int)(start_no_pcr_ts.tv_sec*1000 + start_no_pcr_ts.tv_nsec/1000000);
+         if (diff > 3000) {
+            DVR_INFO("%s no pcr change time from pcr to local time diff[%d]", __func__, diff);
+            if (pcr_rec_len == 0)
+              pcr_rec_len = segment_tell_total_time(p_ctx->segment_handle);
+            p_ctx->index_type = DVR_INDEX_TYPE_LOCAL_CLOCK;
+         }
+      }
+      p_ctx->segment_info.nb_packets = p_ctx->segment_info.size/188;
+
+      if (p_ctx->segment_info.duration - pre_time > DVR_STORE_INFO_TIME) {
+        pre_time = p_ctx->segment_info.duration + DVR_STORE_INFO_TIME;
+        time_t duration = p_ctx->segment_info.duration;
+        if (p_ctx->index_type == DVR_INDEX_TYPE_LOCAL_CLOCK)
+          p_ctx->segment_info.duration = segment_tell_total_time(p_ctx->segment_handle);
+        segment_store_info(p_ctx->segment_handle, &(p_ctx->segment_info));
+        p_ctx->segment_info.duration = duration;
+      }
     } else {
-      DVR_DEBUG(1, "%s can NOT do time index", __func__);
-    }
-    p_ctx->segment_info.nb_packets = p_ctx->segment_info.size/188;
-
-    if (p_ctx->segment_info.duration - pre_time > DVR_STORE_INFO_TIME) {
-      pre_time = p_ctx->segment_info.duration + DVR_STORE_INFO_TIME;
-      segment_store_info(p_ctx->segment_handle, &(p_ctx->segment_info));
+      gettimeofday(&t5, NULL);
     }
     gettimeofday(&t6, NULL);
      /*Event notification*/
-    if (p_ctx->notification_size &&
-        p_ctx->event_notify_fn &&
-        /*!(p_ctx->segment_info.size % p_ctx->notification_size)*/
-    (p_ctx->segment_info.size -p_ctx->last_send_size) >= p_ctx->notification_size&&
-        p_ctx->segment_info.duration > 0  &&
-        p_ctx->state == DVR_RECORD_STATE_STARTED) {
+    DVR_Bool_t condA1 = (p_ctx->notification_size > 0);
+    DVR_Bool_t condA2 = ((p_ctx->segment_info.size-p_ctx->last_send_size) >= p_ctx->notification_size);
+    DVR_Bool_t condA3 = (p_ctx->notification_time > 0);
+    DVR_Bool_t condA4 = ((p_ctx->segment_info.duration-p_ctx->last_send_time) >= p_ctx->notification_time);
+    DVR_Bool_t condA5 = (guarded_size_exceeded);
+    DVR_Bool_t condA6 = (p_ctx->discard_coming_data);
+    DVR_Bool_t condB = (p_ctx->event_notify_fn != NULL);
+    DVR_Bool_t condC = (p_ctx->segment_info.duration > 0);
+    DVR_Bool_t condD = (p_ctx->state == DVR_RECORD_STATE_STARTED);
+    if (((condA1 && condA2) || (condA3 && condA4) || condA5 || condA6)
+      && condB && condC && condD) {
       memset(&record_status, 0, sizeof(record_status));
       //clock_gettime(CLOCK_MONOTONIC, &end_ts);
       p_ctx->last_send_size = p_ctx->segment_info.size;
+      p_ctx->last_send_time = p_ctx->segment_info.duration;
       record_status.state = p_ctx->state;
       record_status.info.id = p_ctx->segment_info.id;
-      record_status.info.duration = p_ctx->segment_info.duration;
+      if (p_ctx->index_type == DVR_INDEX_TYPE_LOCAL_CLOCK)
+        record_status.info.duration = segment_tell_total_time(p_ctx->segment_handle);
+      else
+        record_status.info.duration = p_ctx->segment_info.duration;
       record_status.info.size = p_ctx->segment_info.size;
       record_status.info.nb_packets = p_ctx->segment_info.size/188;
       p_ctx->event_notify_fn(DVR_RECORD_EVENT_STATUS, &record_status, p_ctx->event_userdata);
-      DVR_DEBUG(1, "%s notify record status, state:%d, id:%lld, duration:%ld ms, size:%zu loc[%s]",
+      DVR_INFO("%s notify record status, state:%d, id:%lld, duration:%ld ms, size:%zu loc[%s]",
           __func__, record_status.state,
           record_status.info.id, record_status.info.duration,
           record_status.info.size, p_ctx->location);
     }
     gettimeofday(&t7, NULL);
 #ifdef DEBUG_PERFORMANCE
-    DVR_DEBUG(1, "record count, read:%dms, encrypt:%dms, write:%dms, index:%dms, store:%dms, notify:%dms total:%dms read len:%zd ",
+    DVR_INFO("record count, read:%dms, encrypt:%dms, write:%dms, index:%dms, store:%dms, notify:%dms total:%dms read len:%zd notify [%d]diff[%d]",
         get_diff_time(t1, t2), get_diff_time(t2, t3), get_diff_time(t3, t4), get_diff_time(t4, t5),
-        get_diff_time(t5, t6), get_diff_time(t6, t7), get_diff_time(t1, t5), len);
+        get_diff_time(t5, t6), get_diff_time(t6, t7), get_diff_time(t1, t5), len,
+        p_ctx->notification_time,p_ctx->segment_info.duration -p_ctx->last_send_time);
 #endif
+    if (len == 0) {
+      usleep(20*1000);
+    }
   }
 end:
   free((void *)buf);
   free((void *)buf_out);
-  DVR_DEBUG(1, "exit %s", __func__);
+  DVR_INFO("exit %s", __func__);
   return NULL;
 }
 
@@ -413,7 +518,7 @@
 {
   DVR_RecordContext_t *p_ctx;
   Record_DeviceOpenParams_t dev_open_params;
-  int ret;
+  int ret = DVR_SUCCESS;
   uint32_t i;
 
   DVR_RETURN_IF_FALSE(p_handle);
@@ -427,23 +532,27 @@
   DVR_RETURN_IF_FALSE(i < MAX_DVR_RECORD_SESSION_COUNT);
   DVR_RETURN_IF_FALSE(record_ctx[i].state == DVR_RECORD_STATE_CLOSED);
   p_ctx = &record_ctx[i];
-  DVR_DEBUG(1, "%s , current state:%d, dmx_id:%d, notification_size:%zu, flags:%d, keylen:%d ",
+  DVR_INFO("%s , current state:%d, dmx_id:%d, notification_size:%zu, flags:%d, keylen:%d ",
         __func__, p_ctx->state, params->dmx_dev_id,
-	params->notification_size,
-	params->flags, params->keylen);
+    params->notification_size,
+    params->flags, params->keylen);
 
   /*Process event params*/
   p_ctx->notification_size = params->notification_size;
+  p_ctx->notification_time = params->notification_time;
+
   p_ctx->event_notify_fn = params->event_fn;
   p_ctx->event_userdata = params->event_userdata;
   p_ctx->last_send_size = 0;
+  p_ctx->last_send_time = 0;
+  p_ctx->pts = ULLONG_MAX;
 
   if (params->keylen > 0) {
     p_ctx->cryptor = am_crypt_des_open(params->clearkey,
-				params->cleariv,
-				params->keylen * 8);
+                params->cleariv,
+                params->keylen * 8);
     if (!p_ctx->cryptor)
-      DVR_DEBUG(1, "%s , open des cryptor failed!!!\n", __func__);
+      DVR_INFO("%s , open des cryptor failed!!!\n", __func__);
   } else {
     p_ctx->cryptor = NULL;
   }
@@ -459,25 +568,28 @@
     p_ctx->is_vod = 0;
     /* data from dmx, normal dvr case */
     dev_open_params.dmx_dev_id = params->dmx_dev_id;
+    //set dvr flush size
     dev_open_params.buf_size = (params->flush_size > 0 ? params->flush_size : RECORD_BLOCK_SIZE);
+    //set dvbcore ringbuf size
     dev_open_params.ringbuf_size = params->ringbuf_size;
-    if (p_ctx->is_new_dmx)
-      dev_open_params.buf_size = NEW_DEVICE_RECORD_BLOCK_SIZE * 30;
+
     ret = record_device_open(&p_ctx->dev_handle, &dev_open_params);
     if (ret != DVR_SUCCESS) {
-      DVR_DEBUG(1, "%s, open record devices failed", __func__);
+      DVR_INFO("%s, open record devices failed", __func__);
       return DVR_FAILURE;
     }
   }
 
   p_ctx->block_size = (params->flush_size > 0 ? params->flush_size : RECORD_BLOCK_SIZE);
-  if (p_ctx->is_new_dmx)
-      p_ctx->block_size = NEW_DEVICE_RECORD_BLOCK_SIZE * 30;
+
   p_ctx->enc_func = NULL;
   p_ctx->enc_userdata = NULL;
   p_ctx->is_secure_mode = 0;
   p_ctx->state = DVR_RECORD_STATE_OPENED;
-  DVR_DEBUG(1, "%s, block_size:%d is_new:%d", __func__, p_ctx->block_size, p_ctx->is_new_dmx);
+  p_ctx->force_sysclock = params->force_sysclock;
+  p_ctx->guarded_segment_size = params->guarded_segment_size;
+  p_ctx->discard_coming_data = DVR_FALSE;
+  DVR_INFO("%s, block_size:%d is_new:%d", __func__, p_ctx->block_size, p_ctx->is_new_dmx);
   *p_handle = p_ctx;
   return DVR_SUCCESS;
 }
@@ -485,7 +597,7 @@
 int dvr_record_close(DVR_RecordHandle_t handle)
 {
   DVR_RecordContext_t *p_ctx;
-  int ret;
+  int ret = DVR_SUCCESS;
   uint32_t i;
 
   p_ctx = (DVR_RecordContext_t *)handle;
@@ -495,7 +607,7 @@
   }
   DVR_RETURN_IF_FALSE(p_ctx == &record_ctx[i]);
 
-  DVR_DEBUG(1, "%s , current state:%d", __func__, p_ctx->state);
+  DVR_INFO("%s , current state:%d", __func__, p_ctx->state);
   DVR_RETURN_IF_FALSE(p_ctx->state != DVR_RECORD_STATE_CLOSED);
   if (p_ctx->cryptor) {
     am_crypt_des_close(p_ctx->cryptor);
@@ -506,10 +618,10 @@
   } else {
     ret = record_device_close(p_ctx->dev_handle);
     if (ret != DVR_SUCCESS) {
-      DVR_DEBUG(1, "%s, failed", __func__);
+      DVR_INFO("%s, failed", __func__);
     }
   }
-
+  memset(p_ctx, 0, sizeof(DVR_RecordContext_t));
   p_ctx->state = DVR_RECORD_STATE_CLOSED;
   return ret;
 }
@@ -517,7 +629,7 @@
 int dvr_record_pause(DVR_RecordHandle_t handle)
 {
   DVR_RecordContext_t *p_ctx;
-  int ret;
+  int ret = DVR_SUCCESS;
   uint32_t i;
 
   p_ctx = (DVR_RecordContext_t *)handle;
@@ -527,7 +639,7 @@
   }
   DVR_RETURN_IF_FALSE(p_ctx == &record_ctx[i]);
 
-  DVR_DEBUG(1, "%s , current state:%d", __func__, p_ctx->state);
+  DVR_INFO("%s , current state:%d", __func__, p_ctx->state);
   DVR_RETURN_IF_FALSE(p_ctx->state != DVR_RECORD_STATE_CLOSED);
 
   if (p_ctx->is_vod) {
@@ -541,7 +653,7 @@
 int dvr_record_resume(DVR_RecordHandle_t handle)
 {
   DVR_RecordContext_t *p_ctx;
-  int ret;
+  int ret = DVR_SUCCESS;
   uint32_t i;
 
   p_ctx = (DVR_RecordContext_t *)handle;
@@ -551,7 +663,7 @@
   }
   DVR_RETURN_IF_FALSE(p_ctx == &record_ctx[i]);
 
-  DVR_DEBUG(1, "%s , current state:%d", __func__, p_ctx->state);
+  DVR_INFO("%s , current state:%d", __func__, p_ctx->state);
   DVR_RETURN_IF_FALSE(p_ctx->state != DVR_RECORD_STATE_CLOSED);
 
   if (p_ctx->is_vod) {
@@ -576,7 +688,7 @@
 {
   DVR_RecordContext_t *p_ctx;
   Segment_OpenParams_t open_params;
-  int ret;
+  int ret = DVR_SUCCESS;
   uint32_t i;
 
   p_ctx = (DVR_RecordContext_t *)handle;
@@ -586,7 +698,7 @@
   }
   DVR_RETURN_IF_FALSE(p_ctx == &record_ctx[i]);
 
-  DVR_DEBUG(1, "%s , current state:%d pids:%d params->location:%s", __func__, p_ctx->state, params->segment.nb_pids, params->location);
+  DVR_INFO("%s , current state:%d pids:%d params->location:%s", __func__, p_ctx->state, params->segment.nb_pids, params->location);
   DVR_RETURN_IF_FALSE(p_ctx->state != DVR_RECORD_STATE_STARTED);
   DVR_RETURN_IF_FALSE(p_ctx->state != DVR_RECORD_STATE_CLOSED);
   DVR_RETURN_IF_FALSE(params);
@@ -596,6 +708,7 @@
   memcpy(open_params.location, params->location, sizeof(params->location));
   open_params.segment_id = params->segment.segment_id;
   open_params.mode = SEGMENT_MODE_WRITE;
+  open_params.force_sysclock = p_ctx->force_sysclock;
 
   ret = segment_open(&open_params, &p_ctx->segment_handle);
   DVR_RETURN_IF_FALSE(ret == DVR_SUCCESS);
@@ -623,6 +736,7 @@
   }
 
   ret = segment_store_info(p_ctx->segment_handle, &p_ctx->segment_info);
+  DVR_RETURN_IF_FALSE(ret == DVR_SUCCESS);
 
   p_ctx->state = DVR_RECORD_STATE_STARTED;
   if (!p_ctx->is_vod)
@@ -635,7 +749,7 @@
 {
   DVR_RecordContext_t *p_ctx;
   Segment_OpenParams_t open_params;
-  int ret;
+  int ret = DVR_SUCCESS;
   uint32_t i;
   loff_t pos;
 
@@ -646,7 +760,7 @@
   }
   DVR_RETURN_IF_FALSE(p_ctx == &record_ctx[i]);
 
-  DVR_DEBUG(1, "%s , current state:%d p_ctx->location:%s", __func__, p_ctx->state, p_ctx->location);
+  DVR_INFO("%s , current state:%d p_ctx->location:%s", __func__, p_ctx->state, p_ctx->location);
   DVR_RETURN_IF_FALSE(p_ctx->state == DVR_RECORD_STATE_STARTED);
   //DVR_RETURN_IF_FALSE(p_ctx->state != DVR_RECORD_STATE_CLOSED);
   DVR_RETURN_IF_FALSE(params);
@@ -669,8 +783,8 @@
 
   ret = segment_store_info(p_ctx->segment_handle, p_info);
   DVR_RETURN_IF_FALSE(ret == DVR_SUCCESS);
-
-  DVR_DEBUG(1, "%s dump segment info, id:%lld, nb_pids:%d, duration:%ld ms, size:%zu, nb_packets:%d params->segment.nb_pids:%d",
+  segment_store_allInfo(p_ctx->segment_handle, p_info);
+  DVR_INFO("%s dump segment info, id:%lld, nb_pids:%d, duration:%ld ms, size:%zu, nb_packets:%d params->segment.nb_pids:%d",
       __func__, p_info->id, p_info->nb_pids, p_info->duration, p_info->size, p_info->nb_packets, params->segment.nb_pids);
 
   /*Close current segment*/
@@ -681,8 +795,10 @@
   memcpy(open_params.location, p_ctx->location, sizeof(p_ctx->location));
   open_params.segment_id = params->segment.segment_id;
   open_params.mode = SEGMENT_MODE_WRITE;
-  DVR_DEBUG(1, "%s: p_ctx->location:%s  params->location:%s", __func__, p_ctx->location,params->location);
-
+  open_params.force_sysclock = p_ctx->force_sysclock;
+  DVR_INFO("%s: p_ctx->location:%s  params->location:%s", __func__, p_ctx->location,params->location);
+  p_ctx->last_send_size = 0;
+  p_ctx->last_send_time = 0;
   ret = segment_open(&open_params, &p_ctx->segment_handle);
   DVR_RETURN_IF_FALSE(ret == DVR_SUCCESS);
   /*process params*/
@@ -699,22 +815,22 @@
   for (i = 0; i < params->segment.nb_pids; i++) {
     switch (params->segment.pid_action[i]) {
       case DVR_RECORD_PID_CREATE:
-        DVR_DEBUG(1, "%s create pid:%d", __func__, params->segment.pids[i].pid);
+        DVR_INFO("%s create pid:%d", __func__, params->segment.pids[i].pid);
         ret = record_device_add_pid(p_ctx->dev_handle, params->segment.pids[i].pid);
         p_ctx->segment_info.nb_pids++;
         DVR_RETURN_IF_FALSE(ret == DVR_SUCCESS);
         break;
       case DVR_RECORD_PID_KEEP:
-        DVR_DEBUG(1, "%s keep pid:%d", __func__, params->segment.pids[i].pid);
+        DVR_INFO("%s keep pid:%d", __func__, params->segment.pids[i].pid);
         p_ctx->segment_info.nb_pids++;
         break;
       case DVR_RECORD_PID_CLOSE:
-        DVR_DEBUG(1, "%s close pid:%d", __func__, params->segment.pids[i].pid);
+        DVR_INFO("%s close pid:%d", __func__, params->segment.pids[i].pid);
         ret = record_device_remove_pid(p_ctx->dev_handle, params->segment.pids[i].pid);
         DVR_RETURN_IF_FALSE(ret == DVR_SUCCESS);
         break;
       default:
-        DVR_DEBUG(1, "%s wrong action pid:%d", __func__, params->segment.pids[i].pid);
+        DVR_INFO("%s wrong action pid:%d", __func__, params->segment.pids[i].pid);
         return DVR_FAILURE;
     }
   }
@@ -723,6 +839,9 @@
   //DVR_RETURN_IF_FALSE(ret == DVR_SUCCESS);
   /*Update segment info*/
   ret = segment_store_info(p_ctx->segment_handle, &p_ctx->segment_info);
+  DVR_RETURN_IF_FALSE(ret == DVR_SUCCESS);
+  if (p_ctx->pts != ULLONG_MAX)
+    segment_update_pts(p_ctx->segment_handle, p_ctx->pts, 0);
 
   p_ctx->state = DVR_RECORD_STATE_STARTED;
   pthread_create(&p_ctx->thread, NULL, record_thread, p_ctx);
@@ -732,7 +851,7 @@
 int dvr_record_stop_segment(DVR_RecordHandle_t handle, DVR_RecordSegmentInfo_t *p_info)
 {
   DVR_RecordContext_t *p_ctx;
-  int ret;
+  int ret = DVR_SUCCESS;
   uint32_t i;
   loff_t pos;
 
@@ -743,7 +862,7 @@
   }
   DVR_RETURN_IF_FALSE(p_ctx == &record_ctx[i]);
 
-  DVR_DEBUG(1, "%s , current state:%d p_ctx->location:%s", __func__, p_ctx->state, p_ctx->location);
+  DVR_INFO("%s , current state:%d p_ctx->location:%s", __func__, p_ctx->state, p_ctx->location);
   DVR_RETURN_IF_FALSE(p_ctx->state != DVR_RECORD_STATE_STOPPED);
   DVR_RETURN_IF_FALSE(p_ctx->state != DVR_RECORD_STATE_CLOSED);
   DVR_RETURN_IF_FALSE(p_info);/*should support NULL*/
@@ -753,12 +872,12 @@
     p_ctx->segment_info.duration = segment_tell_total_time(p_ctx->segment_handle);
     p_ctx->segment_info.duration = 10*1000; //debug, should delete it
   } else {
+    pthread_join(p_ctx->thread, NULL);
     ret = record_device_stop(p_ctx->dev_handle);
     //DVR_RETURN_IF_FALSE(ret == DVR_SUCCESS);
     if (ret != DVR_SUCCESS)
       goto end;
     //p_ctx->state = DVR_RECORD_STATE_STOPPED;
-    pthread_join(p_ctx->thread, NULL);
   }
 
   //add index file store
@@ -774,11 +893,14 @@
   if (ret != DVR_SUCCESS)
       goto end;
 
-  DVR_DEBUG(1, "%s dump segment info, id:%lld, nb_pids:%d, duration:%ld ms, size:%zu, nb_packets:%d",
+  segment_store_allInfo(p_ctx->segment_handle, p_info);
+
+  DVR_INFO("%s dump segment info, id:%lld, nb_pids:%d, duration:%ld ms, size:%zu, nb_packets:%d",
       __func__, p_info->id, p_info->nb_pids, p_info->duration, p_info->size, p_info->nb_packets);
 
 end:
   ret = segment_close(p_ctx->segment_handle);
+  p_ctx->segment_handle = NULL;
   DVR_RETURN_IF_FALSE(ret == DVR_SUCCESS);
   return DVR_SUCCESS;
 }
@@ -787,7 +909,7 @@
 {
   DVR_RecordContext_t *p_ctx;
   uint32_t i;
-  int ret;
+  int ret = DVR_SUCCESS;
 
   p_ctx = (DVR_RecordContext_t *)handle;
   for (i = 0; i < MAX_DVR_RECORD_SESSION_COUNT; i++) {
@@ -798,7 +920,7 @@
   DVR_RETURN_IF_FALSE(params);
   DVR_RETURN_IF_FALSE(p_resume_size);
 
-  DVR_DEBUG(1, "%s , current state:%d, resume size:%lld", __func__, p_ctx->state, *p_resume_size);
+  DVR_INFO("%s , current state:%d, resume size:%lld", __func__, p_ctx->state, *p_resume_size);
   ret = dvr_record_start_segment(handle, params);
   DVR_RETURN_IF_FALSE(ret == DVR_SUCCESS);
 
@@ -835,7 +957,7 @@
   DVR_RecordContext_t *p_ctx;
   uint32_t i;
   off_t pos = 0;
-  int ret;
+  int ret = DVR_SUCCESS;
   int has_pcr;
 
   p_ctx = (DVR_RecordContext_t *)handle;
@@ -850,12 +972,12 @@
   pos = segment_tell_position(p_ctx->segment_handle);
   has_pcr = record_do_pcr_index(p_ctx, buffer, len);
   if (has_pcr == 0) {
-    /* Pull VOD record shoud use PCR time index */
-    DVR_DEBUG(1, "%s has no pcr, can NOT do time index", __func__);
+    /* Pull VOD record should use PCR time index */
+    DVR_INFO("%s has no pcr, can NOT do time index", __func__);
   }
   ret = segment_write(p_ctx->segment_handle, buffer, len);
   if (ret != len) {
-    DVR_DEBUG(1, "%s write error ret:%d len:%d", __func__, ret, len);
+    DVR_INFO("%s write error ret:%d len:%d", __func__, ret, len);
   }
   p_ctx->segment_info.size += len;
   p_ctx->segment_info.nb_packets = p_ctx->segment_info.size/188;
@@ -876,7 +998,7 @@
   DVR_RETURN_IF_FALSE(p_ctx == &record_ctx[i]);
   DVR_RETURN_IF_FALSE(func);
 
-  DVR_DEBUG(1, "%s , current state:%d", __func__, p_ctx->state);
+  DVR_INFO("%s , current state:%d", __func__, p_ctx->state);
   DVR_RETURN_IF_FALSE(p_ctx->state != DVR_RECORD_STATE_STARTED);
   DVR_RETURN_IF_FALSE(p_ctx->state != DVR_RECORD_STATE_CLOSED);
 
@@ -889,7 +1011,7 @@
 {
   DVR_RecordContext_t *p_ctx;
   uint32_t i;
-  int ret;
+  int ret = DVR_SUCCESS;
 
   p_ctx = (DVR_RecordContext_t *)handle;
   for (i = 0; i < MAX_DVR_RECORD_SESSION_COUNT; i++) {
@@ -900,7 +1022,7 @@
   DVR_RETURN_IF_FALSE(p_secure_buf);
   DVR_RETURN_IF_FALSE(len);
 
-  DVR_DEBUG(1, "%s , current state:%d", __func__, p_ctx->state);
+  DVR_INFO("%s , current state:%d", __func__, p_ctx->state);
   DVR_RETURN_IF_FALSE(p_ctx->state != DVR_RECORD_STATE_STARTED);
   DVR_RETURN_IF_FALSE(p_ctx->state != DVR_RECORD_STATE_CLOSED);
 
@@ -908,6 +1030,7 @@
   DVR_RETURN_IF_FALSE(ret == DVR_SUCCESS);
 
   p_ctx->is_secure_mode = 1;
+  p_ctx->secbuf_size = len;
   return ret;
 }
 
@@ -915,7 +1038,27 @@
 {
   DVR_RecordContext_t *p_ctx;
   uint32_t i;
-  int ret;
+  int ret = DVR_SUCCESS;
+
+  p_ctx = (DVR_RecordContext_t *)handle;
+  for (i = 0; i < MAX_DVR_RECORD_SESSION_COUNT; i++) {
+    if (p_ctx == &record_ctx[i])
+      break;
+  }
+
+  DVR_RETURN_IF_FALSE(p_ctx == &record_ctx[i]);
+
+  if (p_ctx->is_secure_mode == 1)
+    ret = 1;
+  else
+    ret = 0;
+  return ret;
+}
+
+int dvr_record_discard_coming_data(DVR_RecordHandle_t handle, DVR_Bool_t discard)
+{
+  DVR_RecordContext_t *p_ctx;
+  int i;
 
   p_ctx = (DVR_RecordContext_t *)handle;
   for (i = 0; i < MAX_DVR_RECORD_SESSION_COUNT; i++) {
@@ -924,9 +1067,14 @@
   }
   DVR_RETURN_IF_FALSE(p_ctx == &record_ctx[i]);
 
-  if (p_ctx->is_secure_mode == 1)
-    ret = 1;
-  else
-    ret = 0;
-  return ret;
+  if (p_ctx->discard_coming_data != discard) {
+    p_ctx->discard_coming_data = discard;
+    if (discard) {
+      DVR_WARN("%s, start discarding coming data. discard:%d",__func__,discard);
+    } else {
+      DVR_WARN("%s, finish discarding coming data. discard:%d",__func__,discard);
+    }
+  }
+
+  return DVR_TRUE;
 }
diff --git a/src/dvr_segment.c b/src/dvr_segment.c
index d9d36c4..e0f0967 100644
--- a/src/dvr_segment.c
+++ b/src/dvr_segment.c
@@ -17,16 +17,19 @@
 {
   int ret;
   DVR_SegmentFile_t *segment_file = (DVR_SegmentFile_t*)arg;
+  if (segment_file == NULL) {
+    DVR_ERROR("Invalid segment_file pointer");
+    return NULL;
+  }
 
   pthread_detach(pthread_self());
-  DVR_DEBUG(1, "%s try to delete [%s-%lld]", __func__, segment_file->location, segment_file->id);
+  DVR_INFO("%s try to delete [%s-%lld]", __func__, segment_file->location, segment_file->id);
   ret = segment_delete(segment_file->location, segment_file->id);
-  DVR_DEBUG(1, "%s delete segment [%s-%lld] %s", __func__, segment_file->location, segment_file->id,
+  DVR_INFO("%s delete segment [%s-%lld] %s", __func__, segment_file->location, segment_file->id,
       ret == DVR_SUCCESS ? "success" : "failed");
   if (segment_file != NULL) {
     //malloc at delete api.free at this
     free(segment_file);
-    segment_file = NULL;
   }
   return NULL;
 }
@@ -36,24 +39,24 @@
 
   pthread_t thread;
   DVR_SegmentFile_t *segment;
-  //this segment will be free at del thread when used end.if thread
-  //creat error.will be free now.
-  segment = (DVR_SegmentFile_t *)malloc(sizeof(DVR_SegmentFile_t));
 
-  DVR_DEBUG(1, "%s in, %s,id:%lld", __func__, location, segment_id);
-  DVR_RETURN_IF_FALSE(segment);
   DVR_RETURN_IF_FALSE(location);
   DVR_RETURN_IF_FALSE(strlen(location) < DVR_MAX_LOCATION_SIZE);
+  DVR_INFO("In function %s, segment %s's id is %lld", __func__, location, segment_id);
+
+  // Memory allocated here will be freed in segment deletion thread under normal conditions.
+  // In case of thread creation failure, it will be freed right away.
+  segment = (DVR_SegmentFile_t *)malloc(sizeof(DVR_SegmentFile_t));
+  DVR_RETURN_IF_FALSE(segment != NULL);
+
   memset(segment->location, 0, sizeof(segment->location));
   memcpy(segment->location, location, strlen(location));
   segment->id = segment_id;
 
   int ret = pthread_create(&thread, NULL, dvr_segment_thread, segment);
   if (ret != 0) {
-    //creat thread error,need free segment
     if (segment != NULL) {
       free(segment);
-      segment = NULL;
     }
   }
   return DVR_SUCCESS;
@@ -62,20 +65,20 @@
 int dvr_segment_del_by_location(const char *location)
 {
   FILE *fp;
-  char cmd[DVR_MAX_LOCATION_SIZE + 64];
+  char cmd[DVR_MAX_LOCATION_SIZE * 2 + 64];
 
   DVR_RETURN_IF_FALSE(location);
 
-  DVR_DEBUG(1, "%s location:%s", __func__, location);
+  DVR_INFO("%s location:%s", __func__, location);
   {
     /* del file */
     memset(cmd, 0, sizeof(cmd));
-    sprintf(cmd, "rm %s-* %s.list %s.stats", location, location, location);
+    sprintf(cmd, "rm %s-* %s.list %s.stats %s.odb %s.dat", location, location, location, location, location);
     fp = popen(cmd, "r");
     DVR_RETURN_IF_FALSE(fp);
   }
   pclose(fp);
-  DVR_DEBUG(1, "%s location:%s end", __func__, location);
+  DVR_INFO("%s location:%s end", __func__, location);
   return DVR_SUCCESS;
 }
 
@@ -92,14 +95,11 @@
   DVR_RETURN_IF_FALSE(p_segment_nb);
   DVR_RETURN_IF_FALSE(pp_segment_ids);
 
-  //DVR_DEBUG(1, "%s location:%s", __func__, location);
   memset(fpath, 0, sizeof(fpath));
   sprintf(fpath, "%s.list", location);
 
-  if (access(fpath, 0) != -1) {
-    /*the list file is exist*/
-    fp = fopen(fpath, "r");
-    DVR_RETURN_IF_FALSE(fp);
+  fp = fopen(fpath, "r");
+  if (fp != NULL) { /*the list file exists*/
     /*get segment numbers*/
     while (fgets(buf, sizeof(buf), fp) != NULL) {
       i++;
@@ -117,25 +117,25 @@
     }
     *pp_segment_ids = p;
     fclose(fp);
-    DVR_DEBUG(1, "%s location:%s segments:%d",  __func__, location, i);
-  } else {
+    DVR_INFO("%s location:%s segments:%d",  __func__, location, i);
+  } else { /*the list file does not exist*/
     uint32_t id = 0;
-    /*the list file does not exist*/
     memset(cmd, 0, sizeof(cmd));
     sprintf(cmd, "ls -l %s-*.ts | wc -l", location);
     fp = popen(cmd, "r");
     DVR_RETURN_IF_FALSE(fp);
     memset(buf, 0, sizeof(buf));
     if (fgets(buf, sizeof(buf), fp) != NULL) {
-      i = strtoull(buf, NULL, 10);
+      i = strtoul(buf, NULL, 10);
       pclose(fp);
+      DVR_RETURN_IF_FALSE(i>0);
     } else {
       pclose(fp);
+      DVR_ERROR("%s location:%s get null",  __func__, location);
       return DVR_FAILURE;
     }
-    //DVR_DEBUG(1, "%s location:%s   i: %d ls buf:%s", __func__, location, i, buf);
     n = i;
-    p = malloc(n * sizeof(uint64_t));
+
     /*try to get the 1st segment id*/
     memset(cmd, 0, sizeof(cmd));
     sprintf(cmd, "ls %s-*.ts", location);
@@ -144,19 +144,29 @@
     memset(buf, 0, sizeof(buf));
     j = 0;
     snprintf(fpath, sizeof(fpath), "%s-%%d.ts", location);
+
+    // Tainted data issue originating from fgets seem false positive, so we
+    // just suppress it here.
+    // coverity[tainted_data]
+    p = malloc(n * sizeof(uint64_t));
+    if (p == NULL) {
+      DVR_ERROR("%s, Failed to allocate memory with errno:%d (%s)",
+          __func__,errno,strerror(errno));
+      pclose(fp);
+      return DVR_FAILURE;
+    }
+
     while (fgets(buf, sizeof(buf), fp) != NULL) {
-      //DVR_DEBUG(1, "%s buf:%s", __func__, buf);
       if (sscanf(buf, fpath, &id) != 1) {
-        DVR_DEBUG(1, "%s location:%s  buf:%s not get id", __func__, location, buf);
+        DVR_INFO("%s location:%s  buf:%s not get id", __func__, location, buf);
         id = 0;
         n = n -1;
       } else {
-        //DVR_DEBUG(1, "%s location:%s  buf:%s get id:%d", __func__, location, buf, id);
         p[j++] = id;
       }
       memset(buf, 0, sizeof(buf));
     }
-    //DVR_DEBUG(1, "%s location:%s  n=%d j=%d end", __func__, location, n, j);
+    DVR_DEBUG("%s location:%s  n=%d j=%d end", __func__, location, n, j);
     pclose(fp);
     *p_segment_nb = n;
     *pp_segment_ids = p;
@@ -179,12 +189,20 @@
   memcpy(open_params.location, location, strlen(location));
   open_params.segment_id = segment_id;
   open_params.mode = SEGMENT_MODE_READ;
+
+  // Previous location strlen checking againest DVR_MAX_LOCATION_SIZE and
+  // latter memset on open_params ensure that open_params.location is
+  // null-terminated, so the Coverity STRING_NULL error is suppressed here.
+  // coverity[string_null]
   ret = segment_open(&open_params, &segment_handle);
   if (ret == DVR_SUCCESS) {
     ret = segment_load_info(segment_handle, p_info);
+    if (ret != DVR_SUCCESS) {
+      DVR_ERROR("segment_load_info failed with return value %d",ret);
+    }
   }
-  //DVR_DEBUG(1, "%s, id:%lld, nb_pids:%d, duration:%ld ms, size:%zu, nb_packets:%d",
-    //  __func__, p_info->id, p_info->nb_pids, p_info->duration, p_info->size, p_info->nb_packets);
+  DVR_DEBUG("%s, id:%lld, nb_pids:%d, duration:%ld ms, size:%zu, nb_packets:%d",
+      __func__, p_info->id, p_info->nb_pids, p_info->duration, p_info->size, p_info->nb_packets);
   //DVR_RETURN_IF_FALSE(ret == DVR_SUCCESS);
   ret = segment_close(segment_handle);
   DVR_RETURN_IF_FALSE(ret == DVR_SUCCESS);
@@ -192,9 +210,43 @@
   return DVR_SUCCESS;
 }
 
+int dvr_segment_get_allInfo(const char *location, struct list_head *list)
+{
+  int ret;
+  Segment_OpenParams_t open_params;
+  Segment_Handle_t segment_handle;
+
+  DVR_RETURN_IF_FALSE(location);
+  DVR_RETURN_IF_FALSE(list);
+  DVR_RETURN_IF_FALSE(strlen((const char *)location) < DVR_MAX_LOCATION_SIZE);
+
+  memset(&open_params, 0, sizeof(open_params));
+  memcpy(open_params.location, location, strlen(location));
+  open_params.segment_id = 0;
+  open_params.mode = SEGMENT_MODE_READ;
+
+  // Previous location strlen checking againest DVR_MAX_LOCATION_SIZE and
+  // latter memset on open_params ensure that open_params.location is
+  // null-terminated, so the Coverity STRING_NULL error is suppressed here.
+  // coverity[string_null]
+  ret = segment_open(&open_params, &segment_handle);
+  if (ret == DVR_SUCCESS) {
+    ret = segment_load_allInfo(segment_handle, list);
+    if (ret == DVR_FAILURE) {
+      segment_close(segment_handle);
+      return DVR_FAILURE;
+    }
+  }
+  ret = segment_close(segment_handle);
+  DVR_RETURN_IF_FALSE(ret == DVR_SUCCESS);
+
+  return DVR_SUCCESS;
+}
+
+
 int dvr_segment_link(const char *location, uint32_t nb_segments, uint64_t *p_segment_ids)
 {
-  return dvr_segment_link_op(location, nb_segments, p_segment_ids, LSEG_OP_NEW);
+  return dvr_segment_link_op(location, nb_segments, p_segment_ids, SEGMENT_OP_NEW);
 }
 
 int dvr_segment_link_op(const char *location, uint32_t nb_segments, uint64_t *p_segment_ids, int op)
@@ -208,12 +260,12 @@
   DVR_RETURN_IF_FALSE(p_segment_ids);
   DVR_RETURN_IF_FALSE(strlen((const char *)location) < DVR_MAX_LOCATION_SIZE);
 
-  DVR_DEBUG(1, "%s op[%d] location:%s, nb_segments:%d", __func__, op, location, nb_segments);
+  DVR_INFO("%s op[%d] location:%s, nb_segments:%d", __func__, op, location, nb_segments);
   memset(fpath, 0, sizeof(fpath));
   sprintf(fpath, "%s.list", location);
-  fp = fopen(fpath, (op == LSEG_OP_ADD) ? "a+" : "w+");
+  fp = fopen(fpath, (op == SEGMENT_OP_ADD) ? "a+" : "w+");
   if (!fp) {
-    DVR_DEBUG(1, "failed to open list file, err:%d:%s", errno, strerror(errno));
+    DVR_INFO("failed to open list file, err:%d:%s", errno, strerror(errno));
     return DVR_FAILURE;
   }
   for (i = 0; i< nb_segments; i++) {
diff --git a/src/dvr_utils.c b/src/dvr_utils.c
index 1c16aab..40dcfec 100644
--- a/src/dvr_utils.c
+++ b/src/dvr_utils.c
@@ -12,6 +12,12 @@
 #include <cutils/properties.h>
 #endif
 
+#define _GNU_SOURCE
+#define __USE_GNU
+#include <search.h>
+
+static struct hsearch_data  *prop_htab = NULL;
+
 /****************************************************************************
  * Macro definitions
  ***************************************************************************/
@@ -19,95 +25,11 @@
 /****************************************************************************
  * Static functions
  ***************************************************************************/
-int (*Write_Sysfs_ptr)(const char *path, char *value);
-int (*ReadNum_Sysfs_ptr)(const char *path, char *value, int size);
-int (*Read_Sysfs_ptr)(const char *path, char *value);
-
-typedef struct dvr_rw_sysfs_cb_s
-{
-  DVR_Read_Sysfs_Cb readSysfsCb;
-  DVR_Write_Sysfs_Cb writeSysfsCb;
-}dvr_rw_sysfs_cb_t;
-
-dvr_rw_sysfs_cb_t rwSysfsCb = {.readSysfsCb = NULL, .writeSysfsCb = NULL};
-
-typedef struct dvr_rw_prop_cb_s
-{
-  DVR_Read_Prop_Cb readPropCb;
-  DVR_Write_Prop_Cb writePropCb;
-}dvr_rw_prop_cb_t;
-
-dvr_rw_prop_cb_t rwPropCb = {.readPropCb = NULL, .writePropCb = NULL};
-
 
 /****************************************************************************
  * API functions
  ***************************************************************************/
 
-/**\brief regist rw sysfs cb
- * \param[in] fun callback
- * \return
- *   - DVR_SUCCESS
- *   - error
- */
-int dvr_register_rw_sys(DVR_Read_Sysfs_Cb RCb, DVR_Write_Sysfs_Cb WCb)
-{
-
-  if (RCb == NULL || WCb == NULL) {
-    DVR_DEBUG(1, "dvr_register_rw_sys error param is NULL !!");
-    return DVR_FAILURE;
-  }
-  if (!rwSysfsCb.readSysfsCb)
-    rwSysfsCb.readSysfsCb = RCb;
-  if (!rwSysfsCb.writeSysfsCb)
-    rwSysfsCb.writeSysfsCb = WCb;
-  DVR_DEBUG(1, "dvr_register_rw_sys success !!");
-  return DVR_SUCCESS;
-}
-
-/**\brief unregist rw sys cb
- */
-int dvr_unregister_rw_sys()
-{
-  if (rwSysfsCb.readSysfsCb)
-    rwSysfsCb.readSysfsCb = NULL;
-  if (rwSysfsCb.writeSysfsCb)
-    rwSysfsCb.writeSysfsCb = NULL;
-  return DVR_SUCCESS;
-}
-
-/**\brief regist rw prop cb
- * \param[in] fun callback
- * \return
- *   - DVR_SUCCESS
- *   - error
- */
-
-int dvr_rgister_rw_prop(DVR_Read_Prop_Cb RCb, DVR_Write_Prop_Cb WCb)
-{
-  if (RCb == NULL || WCb == NULL) {
-    DVR_DEBUG(1, "dvr_rgister_rw_prop error param is NULL !!");
-    return DVR_FAILURE;
-  }
-
-  if (!rwPropCb.readPropCb)
-    rwPropCb.readPropCb = RCb;
-  if (!rwPropCb.writePropCb)
-    rwPropCb.writePropCb = WCb;
-
-  DVR_DEBUG(1, "dvr_rgister_rw_prop !!");
-  return DVR_SUCCESS;
-}
-
-/**\brief unregist rw prop cb */
-int dvr_unregister_rw_prop()
-{
-  if (rwPropCb.readPropCb)
-    rwPropCb.readPropCb = NULL;
-  if (rwPropCb.writePropCb)
-    rwPropCb.writePropCb = NULL;
-  return DVR_SUCCESS;
-}
 
 /**\brief Write a string cmd to a file
  * \param[in] name, File name
@@ -123,16 +45,10 @@
     return DVR_FAILURE;
   }
 
-  if (rwSysfsCb.writeSysfsCb)
-  {
-    rwSysfsCb.writeSysfsCb(name, cmd);
-    return DVR_SUCCESS;
-  }
-
   fd = open(name, O_WRONLY);
   if (fd == -1)
   {
-    DVR_DEBUG(1, "cannot open file \"%s\"", name);
+    DVR_INFO("cannot open file \"%s\"", name);
     return DVR_FAILURE;
   }
 
@@ -141,7 +57,7 @@
   ret = write(fd, cmd, len);
   if (ret != len)
   {
-    DVR_DEBUG(1, "write failed file:\"%s\" cmd:\"%s\" error:\"%s\"", name, cmd, strerror(errno));
+    DVR_INFO("write failed file:\"%s\" cmd:\"%s\" error:\"%s\"", name, cmd, strerror(errno));
     close(fd);
     return DVR_FAILURE;
   }
@@ -163,86 +79,176 @@
   char *ret;
 
   if (name == NULL || buf == NULL) {
-    DVR_DEBUG(1, "dvr_file_read error param is NULL");
+    DVR_INFO("dvr_file_read error param is NULL");
     return DVR_FAILURE;
   }
 
-  if (rwSysfsCb.readSysfsCb)
-  {
-    rwSysfsCb.readSysfsCb(name, buf, len);
-    return DVR_SUCCESS;
-  }
-
-
   fp = fopen(name, "r");
   if (!fp)
   {
-    DVR_DEBUG(1, "cannot open file \"%s\"", name);
+    DVR_INFO("cannot open file \"%s\"", name);
     return DVR_FAILURE;
   }
 
   ret = fgets(buf, len, fp);
   if (!ret)
   {
-    DVR_DEBUG(1, "read the file:\"%s\" error:\"%s\" failed", name, strerror(errno));
+    DVR_INFO("read the file:\"%s\" error:\"%s\" failed", name, strerror(errno));
   }
 
   fclose(fp);
   return ret ? DVR_SUCCESS : DVR_FAILURE;
 }
 
-
-/**\brief Write a string cmd to a prop
- * \param[in] name, prop name
- * \param[in] cmd, String command
+/**\brief read property value
+ * \param[in] name, property name
+ * \param[out] buf, property value
  * \return DVR_SUCCESS On success
- * \return Error code On failure
+ * \return DVR_FAILURE On failure
  */
-
-int dvr_prop_echo(const char *name, const char *cmd)
-{
-  if (name == NULL || cmd == NULL) {
-    DVR_DEBUG(1, "dvr_prop_echo: error param is NULL");
-    return DVR_FAILURE;
-  }
-
-  if (rwPropCb.writePropCb)
-  {
-    rwPropCb.writePropCb(name, cmd);
-    return DVR_SUCCESS;
-  }
-
-#ifdef __ANDROID_API__
-  property_set(name, cmd);
-#endif
-  DVR_DEBUG(1, "dvr_prop_echo: error writePropCb is NULL, used property_set");
-  return DVR_FAILURE;
-}
-
-/**\brief read prop value
- * \param[in] name, prop name
- * \param[out] buf, store prop node value
- * \return DVR_SUCCESS On success
- * \return Error code On failure
- */
-
 int dvr_prop_read(const char *name, char *buf, int len)
 {
   if (name == NULL || buf == NULL) {
-    DVR_DEBUG(1, "dvr_prop_read: error param is NULL");
+    DVR_ERROR("%s, property name or value buffer is NULL",__func__);
     return DVR_FAILURE;
   }
 
-  if (rwPropCb.readPropCb)
-  {
-    rwPropCb.readPropCb(name, buf, len);
+#ifdef __ANDROID_API__
+  memset(buf,0,len);
+  property_get(name, buf, "");
+  if (strlen(buf)>0) {
+    DVR_INFO("%s, Read property, name:%s, value:%s",__func__,name,buf);
     return DVR_SUCCESS;
   }
+#endif
+
+  if (prop_htab == NULL) {
+    prop_htab = calloc(1,sizeof(struct hsearch_data));
+    if (prop_htab == NULL) {
+      DVR_ERROR("%s, Failed to allocate memory for prop_htab",__func__);
+      return DVR_FAILURE;
+    }
+    if (0 == hcreate_r(100,prop_htab))
+    {
+      DVR_ERROR("%s, Failed to create hash table with hcreate_r",__func__);
+      return DVR_FAILURE;
+    }
+  }
+
+  ENTRY e, *ep;
+  e.key = name;
+  if (hsearch_r(e,FIND,&ep,prop_htab) == 0) {
+    DVR_ERROR("%s, Failed to read property %s",__func__,name);
+    return DVR_FAILURE;
+  }
+
+  strncpy(buf,ep->data,len);
+  DVR_INFO("%s, Read property from hash table, name:%s, value:%s",__func__,name,buf);
+  return DVR_SUCCESS;
+}
+
+/**\brief write property value
+ * \param[in] name, property name
+ * \param[in] value, property value
+ * \return DVR_SUCCESS On success
+ * \return DVR_FAILURE On failure
+ */
+int dvr_prop_write(const char *name, char *value)
+{
+  if (name == NULL || value == NULL) {
+    DVR_ERROR("%s: property name or value buffer is NULL",__func__);
+    return DVR_FAILURE;
+  }
 
 #ifdef __ANDROID_API__
-  property_get(name, buf, "");
+  property_set(name, value);
 #endif
-  DVR_DEBUG(1, "dvr_prop_read: error readPropCb is NULL, used property_get");
-  return DVR_FAILURE;
+
+  if (prop_htab == NULL) {
+    prop_htab = calloc(1,sizeof(struct hsearch_data));
+    if (prop_htab == NULL) {
+      DVR_ERROR("%s, Failed to allocate memory for prop_htab",__func__);
+      return DVR_FAILURE;
+    }
+    if (0 == hcreate_r(100,prop_htab))
+    {
+      DVR_ERROR("%s, Failed to create hash table with hcreate_r",__func__);
+      return DVR_FAILURE;
+    }
+  }
+
+  ENTRY e, *ep;
+  e.key = name;
+  if (hsearch_r(e,FIND,&ep,prop_htab) != 0) {
+    // in case matched item is found
+    free(ep->data);
+    ep->data=strdup(value);
+  } else {
+    // in case no matched item, we need to add new one to hash table
+    e.key=strdup(name);
+    e.data=strdup(value);
+    if ( e.key != NULL && e.data != NULL ) {
+      if (hsearch_r(e,ENTER,&ep,prop_htab) == 0) {
+        DVR_ERROR("%s, Failed to add an entry to hash table %s:%s",__func__,name,value);
+        return DVR_FAILURE;
+      }
+    } else {
+      if (e.key != NULL) {
+        free(e.key);
+      }
+      if (e.data != NULL) {
+        free(e.data);
+      }
+      DVR_ERROR("%s, Failed to duplicate strings %s,%s",__func__,name,value);
+      return DVR_FAILURE;
+    }
+  }
+
+  DVR_INFO("%s, Wrote property to hash table, name:%s, value:%s",__func__,name,value);
+  return DVR_SUCCESS;
+}
+
+/**\brief read int type property value
+ * \param[in] name, property name
+ * \param[in] def, default property value in case any failure
+ * \return int type property value. If any failure default value will be returned instead
+ */
+int dvr_prop_read_int(const char *name, int def)
+{
+  char buf[16] = {0};
+  if (dvr_prop_read(name,buf,sizeof(buf)) == DVR_SUCCESS) {
+    return atoi(buf);
+  }
+  return def;
+}
+
+#define NSEC_PER_SEC 1000000000L
+void clock_timespec_subtract(struct timespec *ts1, struct timespec *ts2, struct timespec *ts3)
+{
+  time_t sec;
+  long nsec;
+  sec = ts1->tv_sec - ts2->tv_sec;
+  nsec = ts1->tv_nsec - ts2->tv_nsec;
+  if (ts1->tv_sec >= 0 && ts1->tv_nsec >=0) {
+    if ((sec < 0 && nsec > 0) || (sec > 0 && nsec >= NSEC_PER_SEC)) {
+      nsec -= NSEC_PER_SEC;
+      sec++;
+    }
+    if (sec > 0 && nsec < 0) {
+      nsec += NSEC_PER_SEC;
+      sec--;
+    }
+  } else {
+    if (nsec <= -NSEC_PER_SEC || nsec >= NSEC_PER_SEC) {
+      nsec += NSEC_PER_SEC;
+      sec--;
+    }
+    if ((sec < 0 && nsec > 0)) {
+      nsec -= NSEC_PER_SEC;
+      sec++;
+    }
+  }
+  ts3->tv_sec = sec;
+  ts3->tv_nsec = nsec;
 }
 
diff --git a/src/dvr_wrapper.c b/src/dvr_wrapper.c
index ca46587..3b5fd1f 100644
--- a/src/dvr_wrapper.c
+++ b/src/dvr_wrapper.c
@@ -13,6 +13,7 @@
 #include "dvr_crypto.h"
 #include "dvr_playback.h"
 #include "dvr_segment.h"
+#include "dvr_utils.h"
 
 #include "AmTsPlayer.h"
 
@@ -20,14 +21,20 @@
 
 #include "dvr_wrapper.h"
 
-#define DVR_WRAPPER_DEBUG(_level, _fmt...) \
-  DVR_DEBUG_FL(_level, "wrapper", _fmt)
+#define WRAPPER_LOG_TAG "libdvr-wrapper"
+#define DVR_WRAPPER_DEBUG(...) DVR_LOG_PRINT(LOG_LV_DEBUG, WRAPPER_LOG_TAG, __VA_ARGS__)
+#define DVR_WRAPPER_INFO(...) DVR_LOG_PRINT(LOG_LV_INFO, WRAPPER_LOG_TAG, __VA_ARGS__)
+#define DVR_WRAPPER_WARN(...) DVR_LOG_PRINT(LOG_LV_WARN, WRAPPER_LOG_TAG, __VA_ARGS__)
+#define DVR_WRAPPER_ERROR(...) DVR_LOG_PRINT(LOG_LV_ERROR, WRAPPER_LOG_TAG, __VA_ARGS__)
+#define DVR_WRAPPER_FATAL(...) DVR_LOG_PRINT(LOG_LV_FATAL, WRAPPER_LOG_TAG, __VA_ARGS__)
 
 /*duration of data to resume if paused with EVT_REACHED_END in timeshifting*/
 #define TIMESHIFT_DATA_DURATION_TO_RESUME (600)
 /*a tolerant gap*/
 #define DVR_PLAYBACK_END_GAP              (1000)
 
+int g_dvr_log_level = LOG_LV_DEFAULT;
+
 enum {
   W_REC      = 1,
   W_PLAYBACK = 2,
@@ -40,8 +47,98 @@
 };
 
 typedef struct {
+  pthread_mutex_t lock;
+  pthread_cond_t  cond;
+  int             inited;
+  int             locked;
+} DVR_WrapperMutex_t;
+
+static void
+wrapper_mutex_init (DVR_WrapperMutex_t *lock)
+{
+  pthread_condattr_t cattr;
+
+  if (lock->inited)
+    return;
+
+  pthread_mutex_init(&lock->lock, NULL);
+
+  pthread_condattr_init(&cattr);
+  pthread_condattr_setclock(&cattr, CLOCK_MONOTONIC);
+  pthread_cond_init(&lock->cond, &cattr);
+  pthread_condattr_destroy(&cattr);
+
+  // It is not necessary to protect code block below with
+  // DVR_WrapperMutex_t.lock, so the following annotation
+  // is given to suppress related Coverity complaint.
+  // coverity[missing_lock]
+  lock->locked = 0;
+  lock->inited = 1;
+}
+
+static int
+wrapper_mutex_lock (DVR_WrapperMutex_t *lock)
+{
+  pthread_mutex_lock(&lock->lock);
+  // This couldn't be a infinite loop as Coverity reported.
+  // Loop can finish when another thread calls wrapper_mutex_unlock.
+  // coverity[loop_condition]
+  while (lock->locked) {
+    pthread_cond_wait(&lock->cond, &lock->lock);
+  }
+  lock->locked = 1;
+  pthread_mutex_unlock(&lock->lock);
+
+  return 0;
+}
+
+static int
+wrapper_mutex_unlock (DVR_WrapperMutex_t *lock)
+{
+  pthread_mutex_lock(&lock->lock);
+  lock->locked = 0;
+  pthread_mutex_unlock(&lock->lock);
+  pthread_cond_signal(&lock->cond);
+
+  return 0;
+}
+
+static int
+wrapper_mutex_timedlock (DVR_WrapperMutex_t *lock, struct timespec *tv)
+{
+  int r = 0;
+
+  pthread_mutex_lock(&lock->lock);
+  if (lock->locked) {
+    //DVR_WRAPPER_DEBUG("Enter cond_timedwait");
+    r = pthread_cond_timedwait(&lock->cond, &lock->lock, tv);
+    //DVR_WRAPPER_DEBUG("Leave cond_timedwait");
+  }
+  if (r == 0) {
+    if (!lock->locked) {
+      lock->locked = 1;
+    } else {
+      r = ETIMEDOUT;
+    }
+  }
+  pthread_mutex_unlock(&lock->lock);
+
+  return r;
+}
+
+#define WRAPPER_RETURN_IF_FALSE_WITH_UNLOCK(expr, lock)\
+  do {\
+    if (!(expr)) {\
+      DVR_INFO("%s-%d failed", __func__, __LINE__);\
+      wrapper_mutex_unlock(lock);\
+      return DVR_FAILURE;\
+    }\
+  } while (0);
+
+
+typedef struct {
   /*make lock the 1st item in the structure*/
-  pthread_mutex_t               lock;
+  DVR_WrapperMutex_t            wrapper_lock;
 
   /*rec or play*/
   int                           type;
@@ -85,6 +182,7 @@
       DVR_Bool_t                      reach_end;
 
       DVR_WrapperInfo_t               obsolete;
+      DVR_Bool_t                      tf_full;
     } playback;
   };
 } DVR_WrapperCtx_t;
@@ -153,7 +251,6 @@
 {
   [0 ... (DVR_WRAPPER_MAX - 1)] =
   {
-    .lock = PTHREAD_MUTEX_INITIALIZER,
     .type = W_REC,
   }
 };
@@ -162,7 +259,6 @@
 {
   [0 ... (DVR_WRAPPER_MAX - 1)] =
   {
-    .lock = PTHREAD_MUTEX_INITIALIZER,
     .type = W_PLAYBACK,
   }
 };
@@ -231,18 +327,18 @@
 
 static DVR_WrapperEventCtx_t *ctx_getEvent(struct list_head *list, pthread_mutex_t *list_lock)
 {
-  DVR_WrapperEventCtx_t *pevt;
+  DVR_WrapperEventCtx_t *p_evt;
 
   pthread_mutex_lock(list_lock);
   if (list_empty(list))
-    pevt = NULL;
+    p_evt = NULL;
   else {
-    pevt = list_first_entry(list, DVR_WrapperEventCtx_t, head);
-    list_del(&pevt->head);
+    p_evt = list_first_entry(list, DVR_WrapperEventCtx_t, head);
+    list_del(&p_evt->head);
   }
   pthread_mutex_unlock(list_lock);
 
-  return pevt;
+  return p_evt;
 }
 
 static inline DVR_WrapperEventCtx_t *ctx_getRecordEvent()
@@ -263,7 +359,7 @@
 
   *padd = *evt;
   pthread_mutex_lock(lock);
-  list_add_tail(&padd->head, list);
+  list_add_tail(padd, list);
   pthread_mutex_unlock(lock);
   return DVR_SUCCESS;
 }
@@ -278,7 +374,7 @@
     pthread_mutex_t *evt_list_lock,
     DVR_WrapperCtx_t *list)
 {
-  DVR_WrapperEventCtx_t *pevt, *pevt_tmp;
+  DVR_WrapperEventCtx_t *p_evt, *p_evt_tmp;
   unsigned long sns[DVR_WRAPPER_MAX];
   int cnt = 0;
   int i;
@@ -293,16 +389,16 @@
 
   /*free evts that not belong to any valid sns*/
   pthread_mutex_lock(evt_list_lock);
-  list_for_each_entry_safe(pevt, pevt_tmp, evt_list, head) {
+  list_for_each_entry_safe(p_evt, p_evt_tmp, evt_list, head) {
     for (i = 0; i < cnt; i++) {
-      if (pevt->sn == sns[i]) {
+      if (p_evt->sn == sns[i]) {
         found = 1;
         break;
       }
     }
     if (!found) {
-      list_del(&pevt->head);
-      ctx_freeEvent(pevt);
+      list_del(&p_evt->head);
+      ctx_freeEvent(p_evt);
     }
   }
   pthread_mutex_unlock(evt_list_lock);
@@ -328,13 +424,13 @@
 
   for (i = 0; i < DVR_WRAPPER_MAX; i++) {
     cnt = &record_list[i];
-    //DVR_WRAPPER_DEBUG(1, "[%d]sn[%d]R:[%s]P:[%s] ...\n", i, cnt->sn, cnt->record.param_open.location, play_location);
+    //DVR_WRAPPER_INFO("[%d]sn[%d]R:[%s]P:[%s] ...\n", i, cnt->sn, cnt->record.param_open.location, play_location);
     if (!strcmp(cnt->record.param_open.location, play_location)) {
-      DVR_WRAPPER_DEBUG(1, "[%d]sn[%d]R:[%s]P:[%s] .found..\n", i, cnt->sn, cnt->record.param_open.location, play_location);
+      DVR_WRAPPER_INFO("[%d]sn[%d]R:[%s]P:[%s] .found..\n", i, cnt->sn, cnt->record.param_open.location, play_location);
       return cnt->sn;
     }
   }
-  DVR_WRAPPER_DEBUG(1, " not found play is recing [%d]", DVR_WRAPPER_MAX);
+  DVR_WRAPPER_INFO(" not found any play is in recording [%d]", DVR_WRAPPER_MAX);
   return 0;
 }
 //check this record is playing file
@@ -346,13 +442,13 @@
     DVR_WrapperCtx_t *cnt;
     for (i = 0; i < DVR_WRAPPER_MAX; i++) {
       cnt = &playback_list[i];
-      //DVR_WRAPPER_DEBUG(1, "[%d]sn[%d]P[%s]R[%s] ...\n", i, cnt->sn, cnt->playback.param_open.location, rec_location);
+      //DVR_WRAPPER_INFO("[%d]sn[%d]P[%s]R[%s] ...\n", i, cnt->sn, cnt->playback.param_open.location, rec_location);
       if (!strcmp(cnt->playback.param_open.location, rec_location)) {
-        DVR_WRAPPER_DEBUG(1, "[%d]sn[%d]P[%s]R[%s] ..found.\n",i, cnt->sn, cnt->playback.param_open.location, rec_location);
+        DVR_WRAPPER_INFO("[%d]sn[%d]P[%s]R[%s] ..found.\n",i, cnt->sn, cnt->playback.param_open.location, rec_location);
         return cnt->sn;
       }
     }
-    DVR_WRAPPER_DEBUG(1, " not found rec is playing [%d]", DVR_WRAPPER_MAX);
+    DVR_WRAPPER_INFO(" not found rec is playing [%d]", DVR_WRAPPER_MAX);
     return 0;
 }
 
@@ -360,8 +456,10 @@
 {
   int i;
   for (i = 0; i < DVR_WRAPPER_MAX; i++) {
-    if (list[i].sn == sn)
+    if (list[i].sn == sn) {
+      wrapper_mutex_init(&list[i].wrapper_lock);
       return &list[i];
+    }
   }
   return NULL;
 }
@@ -392,13 +490,13 @@
 {
   pthread_mutex_lock(&ctx->lock);
   if (ctx->running == 0) {
-    pthread_condattr_t attr;
+    pthread_condattr_t attr = {0};
     pthread_condattr_setclock(&attr, CLOCK_MONOTONIC);
     pthread_cond_init(&ctx->cond, &attr);
     pthread_condattr_destroy(&attr);
-    DVR_WRAPPER_DEBUG(1, "start wrapper thread(%s) ...\n", ctx->name);
+    DVR_WRAPPER_INFO("start wrapper thread(%s) ...\n", ctx->name);
     pthread_create(&ctx->thread, NULL, thread_fn, ctx);
-    DVR_WRAPPER_DEBUG(1, "wrapper thread(%s) started\n", ctx->name);
+    DVR_WRAPPER_INFO("wrapper thread(%s) started\n", ctx->name);
   }
   ctx->running++;
   pthread_mutex_unlock(&ctx->lock);
@@ -413,9 +511,9 @@
     pthread_cond_broadcast(&ctx->cond);
     pthread_mutex_unlock(&ctx->lock);
 
-    DVR_WRAPPER_DEBUG(1, "stop wrapper thread(%s) ...\n", ctx->name);
+    DVR_WRAPPER_INFO("stop wrapper thread(%s) ...\n", ctx->name);
     pthread_join(ctx->thread, NULL);
-    DVR_WRAPPER_DEBUG(1, "wrapper thread(%s) stopped\n", ctx->name);
+    DVR_WRAPPER_INFO("wrapper thread(%s) stopped\n", ctx->name);
 
     pthread_mutex_lock(&ctx->lock);
     if (!ctx->running) /*protect*/
@@ -484,98 +582,75 @@
   return 0;
 }
 
-static void get_timeout_real(int timeout, struct timespec *ts)
-{
-  struct timespec ots;
-  int left, diff;
-
-  clock_gettime(CLOCK_REALTIME, &ots);
-
-  ts->tv_sec  = ots.tv_sec + timeout/1000;
-  ts->tv_nsec = ots.tv_nsec;
-
-  left = timeout % 1000;
-  left *= 1000000;
-  diff = 1000000000-ots.tv_nsec;
-
-  if (diff <= left) {
-    ts->tv_sec++;
-    ts->tv_nsec = left-diff;
-  } else {
-    ts->tv_nsec += left;
-  }
-}
-
 /*return condition, locked if condition == true*/
-static int wrapper_mutex_lock_if(pthread_mutex_t *lock, int *condition)
+static int wrapper_mutex_lock_if(DVR_WrapperMutex_t *lock, int *condition)
 {
   int r2;
   do {
     struct timespec rt2;
-    /*android use real time for mutex timedlock*/
-    get_timeout_real(10, &rt2);
-    r2 = pthread_mutex_timedlock(lock, &rt2);
+    get_timespec_timeout(10, &rt2);
+    r2 = wrapper_mutex_timedlock(lock, &rt2);
   } while (*condition && (r2 == ETIMEDOUT));
 
   if (!(*condition) && (r2 == 0))
-    pthread_mutex_unlock(lock);
+    wrapper_mutex_unlock(lock);
 
   return *condition;
 }
 
 static void *wrapper_task(void *arg)
 {
-  DVR_WrapperThreadCtx_t *tctx = (DVR_WrapperThreadCtx_t *)arg;
+  DVR_WrapperThreadCtx_t *thread_ctx = (DVR_WrapperThreadCtx_t *)arg;
   DVR_WrapperEventCtx_t *evt;
 
-  pthread_mutex_lock(&tctx->lock);
+  pthread_mutex_lock(&thread_ctx->lock);
 
-  while (tctx->running) {
+  while (thread_ctx->running) {
     {
       int ret;
 
-      evt = (tctx->type == W_REC)? ctx_getRecordEvent() : ctx_getPlaybackEvent();
+      evt = (thread_ctx->type == W_REC)? ctx_getRecordEvent() : ctx_getPlaybackEvent();
       if (!evt)
-        ret = wrapper_threadWait(tctx);
+        ret = wrapper_threadWait(thread_ctx);
     }
 
     while (evt) {
       DVR_WrapperCtx_t *ctx = (evt->type == W_REC)?
         ctx_getRecord(evt->sn) : ctx_getPlayback(evt->sn);
       if (ctx == NULL) {
-        DVR_WRAPPER_DEBUG(1, "warp not get ctx.free event..\n");
+        DVR_WRAPPER_INFO("warp not get ctx.free event..\n");
         goto processed;
       }
-      DVR_WRAPPER_DEBUG(1, "start name(%s) sn(%d) running(%d) type(%d)\n", tctx->name, (int)ctx->sn, tctx->running, tctx->type);
-      if (tctx->running) {
+      DVR_WRAPPER_INFO("start name(%s) sn(%d) running(%d) type(%d)\n", thread_ctx->name, (int)ctx->sn, thread_ctx->running, thread_ctx->type);
+      if (thread_ctx->running) {
         /*
           continue not break,
           make all events consumed, or mem leak
         */
-        if (!wrapper_mutex_lock_if(&ctx->lock, &tctx->running))
+        if (!wrapper_mutex_lock_if(&ctx->wrapper_lock, &thread_ctx->running))
             goto processed;
 
         if (ctx_valid(ctx)) {
           /*double check after lock*/
           if (evt->sn == ctx->sn) {
-            pthread_mutex_unlock(&tctx->lock);
+            pthread_mutex_unlock(&thread_ctx->lock);
             process_handleEvents(evt, ctx);
-            pthread_mutex_lock(&tctx->lock);
+            pthread_mutex_lock(&thread_ctx->lock);
           }
         }
-        pthread_mutex_unlock(&ctx->lock);
+        wrapper_mutex_unlock(&ctx->wrapper_lock);
       }
 
 processed:
       ctx_freeEvent(evt);
 
-      evt = (tctx->type == W_REC)? ctx_getRecordEvent() : ctx_getPlaybackEvent();
+      evt = (thread_ctx->type == W_REC)? ctx_getRecordEvent() : ctx_getPlaybackEvent();
     }
-    DVR_WRAPPER_DEBUG(1, "start name(%s) running(%d) type(%d) con...\n", tctx->name, tctx->running, tctx->type);
+    DVR_WRAPPER_INFO("start name(%s) running(%d) type(%d) con...\n", thread_ctx->name, thread_ctx->running, thread_ctx->type);
   }
 
-  pthread_mutex_unlock(&tctx->lock);
-  DVR_WRAPPER_DEBUG(1, "end name(%s) running(%d) type(%d) end...\n", tctx->name, tctx->running, tctx->type);
+  pthread_mutex_unlock(&thread_ctx->lock);
+  DVR_WRAPPER_INFO("end name(%s) running(%d) type(%d) end...\n", thread_ctx->name, thread_ctx->running, thread_ctx->type);
   return NULL;
 }
 
@@ -599,65 +674,69 @@
 
 static inline void ctx_freeSegments(DVR_WrapperCtx_t *ctx)
 {
-  DVR_WrapperPlaybackSegmentInfo_t *pseg, *pseg_tmp;
-  list_for_each_entry_safe(pseg, pseg_tmp, &ctx->segments, head) {
-    list_del(&pseg->head);
-    free(pseg);
+  DVR_WrapperPlaybackSegmentInfo_t *p_seg, *p_seg_tmp;
+  list_for_each_entry_safe(p_seg, p_seg_tmp, &ctx->segments, head) {
+    list_del(&p_seg->head);
+    free(p_seg);
   }
 }
 
-static inline void _updatePlaybackSegment(DVR_WrapperPlaybackSegmentInfo_t *pseg,
+static inline void _updatePlaybackSegment(DVR_WrapperPlaybackSegmentInfo_t *p_seg,
     DVR_RecordSegmentInfo_t *seg_info, int update_flags, DVR_WrapperCtx_t *ctx)
 {
   (void)ctx;
   if ((update_flags & U_PIDS) && (update_flags & U_STAT))
-    pseg->seg_info = *seg_info;
+    p_seg->seg_info = *seg_info;
   else if (update_flags & U_PIDS) {
-    pseg->seg_info.nb_pids = seg_info->nb_pids;
-    memcpy(pseg->seg_info.pids, seg_info->pids, sizeof(pseg->seg_info.pids));
+    p_seg->seg_info.nb_pids = seg_info->nb_pids;
+    memcpy(p_seg->seg_info.pids, seg_info->pids, sizeof(p_seg->seg_info.pids));
   } else if (update_flags & U_STAT) {
-    pseg->seg_info.duration = seg_info->duration;
-    pseg->seg_info.size = seg_info->size;
-    pseg->seg_info.nb_packets = seg_info->nb_packets;
+    p_seg->seg_info.duration = seg_info->duration;
+    p_seg->seg_info.size = seg_info->size;
+    p_seg->seg_info.nb_packets = seg_info->nb_packets;
   }
   //update current segment duration on timeshift mode
   if (ctx->playback.param_open.is_timeshift
       || ctx_isPlay_recording(ctx->playback.param_open.location))
-    dvr_playback_update_duration(ctx->playback.player,pseg->seg_info.id,pseg->seg_info.duration);
+    dvr_playback_update_duration(ctx->playback.player,p_seg->seg_info.id,p_seg->seg_info.duration);
   /*no changes
   DVR_PlaybackSegmentFlag_t flags;
-  pseg->playback_info.segment_id = pseg->seg_info.id;
-  strncpy(pseg->playback_info.location,
-    ctx->playback.param_open.location, sizeof(pseg->playback_info.location));
-  pseg->playback_info.pids = ctx->playback.pids_req;
+  p_seg->playback_info.segment_id = p_seg->seg_info.id;
+  strncpy(p_seg->playback_info.location,
+    ctx->playback.param_open.location, sizeof(p_seg->playback_info.location));
+  p_seg->playback_info.pids = ctx->playback.pids_req;
   flags = DVR_PLAYBACK_SEGMENT_DISPLAYABLE | DVR_PLAYBACK_SEGMENT_CONTINUOUS;
   if (ctx->record.param_open.flags | DVR_RECORD_FLAG_SCRAMBLED)
     flags |= DVR_PLAYBACK_SEGMENT_ENCRYPTED;
-  pseg->playback_info.flags = flags;
+  p_seg->playback_info.flags = flags;
   */
 }
 
 static int wrapper_updatePlaybackSegment(DVR_WrapperCtx_t *ctx, DVR_RecordSegmentInfo_t *seg_info, int update_flags)
 {
-  DVR_WrapperPlaybackSegmentInfo_t *pseg;
+  DVR_WrapperPlaybackSegmentInfo_t *p_seg;
 
-  DVR_WRAPPER_DEBUG(1, "timeshift, update playback segments(wrapper), seg:%lld t/s/p(%ld/%zu/%u)\n",
+  DVR_WRAPPER_INFO("timeshift, update playback segments(wrapper), seg:%lld t/s/p(%ld/%zu/%u)\n",
     seg_info->id, seg_info->duration, seg_info->size, seg_info->nb_packets);
 
   if (list_empty(&ctx->segments)) {
-    DVR_WRAPPER_DEBUG(1, "timeshift, update while no segment exists, ignore\n");
+    DVR_WRAPPER_INFO("timeshift, update while no segment exists, ignore\n");
     return DVR_SUCCESS;
   }
 
   /*normally, the last segment added will be updated*/
-  pseg =
+  p_seg =
     list_first_entry(&ctx->segments, DVR_WrapperPlaybackSegmentInfo_t, head);
-  if (pseg->seg_info.id == seg_info->id) {
-    _updatePlaybackSegment(pseg, seg_info, update_flags, ctx);
+  if (p_seg->seg_info.id == seg_info->id) {
+    _updatePlaybackSegment(p_seg, seg_info, update_flags, ctx);
   } else {
-    list_for_each_entry_reverse(pseg, &ctx->segments, head) {
-      if (pseg->seg_info.id == seg_info->id) {
-        _updatePlaybackSegment(pseg, seg_info, update_flags, ctx);
+    // This error is suppressed as the macro code is picked from kernel.
+    // prefetch() here incurring self_assign is used to avoid some compiling
+    // warnings.
+    // coverity[self_assign]
+    list_for_each_entry_reverse(p_seg, &ctx->segments, head) {
+      if (p_seg->seg_info.id == seg_info->id) {
+        _updatePlaybackSegment(p_seg, seg_info, update_flags, ctx);
         break;
       }
     }
@@ -684,7 +763,7 @@
           ctx->playback.last_event = DVR_PLAYBACK_EVENT_TRANSITION_OK;
 
       error = dvr_playback_resume(ctx->playback.player);
-      DVR_WRAPPER_DEBUG(1, "timeshift, resume playback(sn:%ld) (%d) id/dur: rec(%lld/%ld) play(%lld/%u)\n",
+      DVR_WRAPPER_INFO("timeshift, resume playback(sn:%ld) (%d) id/dur: rec(%lld/%ld) play(%lld/%u)\n",
         ctx->sn, error,
         seg_info->id, seg_info->duration,
         ctx->playback.seg_status.segment_id, ctx->playback.seg_status.time_cur);
@@ -694,36 +773,40 @@
   return DVR_SUCCESS;
 }
 
-static void _updateRecordSegment(DVR_WrapperRecordSegmentInfo_t *pseg,
+static void _updateRecordSegment(DVR_WrapperRecordSegmentInfo_t *p_seg,
   DVR_RecordSegmentInfo_t *seg_info, int update_flags, DVR_WrapperCtx_t *ctx)
 {
   (void)ctx;
   if ((update_flags & U_PIDS) && (update_flags & U_STAT))
-    pseg->info = *seg_info;
+    p_seg->info = *seg_info;
   else if (update_flags & U_PIDS) {
-    pseg->info.nb_pids = seg_info->nb_pids;
-    memcpy(pseg->info.pids, seg_info->pids, sizeof(pseg->info.pids));
+    p_seg->info.nb_pids = seg_info->nb_pids;
+    memcpy(p_seg->info.pids, seg_info->pids, sizeof(p_seg->info.pids));
   } else if (update_flags & U_STAT) {
-    pseg->info.duration = seg_info->duration;
-    pseg->info.size = seg_info->size;
-    pseg->info.nb_packets = seg_info->nb_packets;
+    p_seg->info.duration = seg_info->duration;
+    p_seg->info.size = seg_info->size;
+    p_seg->info.nb_packets = seg_info->nb_packets;
   }
 }
 
 static int wrapper_updateRecordSegment(DVR_WrapperCtx_t *ctx, DVR_RecordSegmentInfo_t *seg_info, int update_flags)
 {
-  DVR_WrapperRecordSegmentInfo_t *pseg = NULL;
+  DVR_WrapperRecordSegmentInfo_t *p_seg = NULL;
 
   /*normally, the last segment added will be updated*/
   if (!list_empty(&ctx->segments)) {
-    pseg =
+    p_seg =
       list_first_entry(&ctx->segments, DVR_WrapperRecordSegmentInfo_t, head);
-    if (pseg->info.id == seg_info->id) {
-      _updateRecordSegment(pseg, seg_info, update_flags, ctx);
+    if (p_seg->info.id == seg_info->id) {
+      _updateRecordSegment(p_seg, seg_info, update_flags, ctx);
     } else {
-      list_for_each_entry_reverse(pseg, &ctx->segments, head) {
-        if (pseg->info.id == seg_info->id) {
-          _updateRecordSegment(pseg, seg_info, update_flags, ctx);
+      // This error is suppressed as the macro code is picked from kernel.
+      // prefetch() here incurring self_assign is used to avoid some compiling
+      // warnings.
+      // coverity[self_assign]
+      list_for_each_entry_reverse(p_seg, &ctx->segments, head) {
+        if (p_seg->info.id == seg_info->id) {
+          _updateRecordSegment(p_seg, seg_info, update_flags, ctx);
           break;
         }
       }
@@ -749,13 +832,13 @@
       ctx_playback = ctx_getPlayback(sn);
 
     if (ctx_playback) {
-      pthread_mutex_lock(&ctx_playback->lock);
+      wrapper_mutex_lock(&ctx_playback->wrapper_lock);
       if (ctx_valid(ctx_playback)
           && (ctx_playback->sn == sn_timeshift_playback ||
               ctx_playback->sn == sn)) {
           wrapper_updatePlaybackSegment(ctx_playback, seg_info, update_flags);
       }
-      pthread_mutex_unlock(&ctx_playback->lock);
+      wrapper_mutex_unlock(&ctx_playback->wrapper_lock);
     }
   }
 
@@ -767,34 +850,41 @@
     DVR_PlaybackPids_t *p_pids,
     DVR_PlaybackSegmentFlag_t flags)
 {
-  DVR_WrapperPlaybackSegmentInfo_t *pseg;
+  DVR_WrapperPlaybackSegmentInfo_t *p_seg;
   int error;
 
   error = 0;
-  pseg = (DVR_WrapperPlaybackSegmentInfo_t *)calloc(1, sizeof(DVR_WrapperPlaybackSegmentInfo_t));
-  if (!pseg) {
+  p_seg = (DVR_WrapperPlaybackSegmentInfo_t *)calloc(1, sizeof(DVR_WrapperPlaybackSegmentInfo_t));
+  if (!p_seg) {
     error = DVR_FAILURE;
-    DVR_WRAPPER_DEBUG(1, "memory fail\n");
+    DVR_WRAPPER_INFO("memory fail\n");
     return error;
   }
 
-  /*copy the orignal segment info*/
-  pseg->seg_info = *seg_info;
+  /*copy the original segment info*/
+  p_seg->seg_info = *seg_info;
   /*generate the segment info used in playback*/
-  pseg->playback_info.segment_id = pseg->seg_info.id;
-  strncpy(pseg->playback_info.location, ctx->playback.param_open.location, sizeof(pseg->playback_info.location));
-  pseg->playback_info.pids = *p_pids;
-  pseg->playback_info.flags = flags;
-  list_add(&pseg->head, &ctx->segments);
-  pseg->playback_info.duration = pseg->seg_info.duration;
+  p_seg->playback_info.segment_id = p_seg->seg_info.id;
+  const int len = strlen(ctx->playback.param_open.location);
+  if (len >= DVR_MAX_LOCATION_SIZE || len <= 0) {
+    DVR_WRAPPER_ERROR("Invalid playback.param_open.location length %d", len);
+    free(p_seg);
+    return DVR_FAILURE;
+  }
+  strncpy(p_seg->playback_info.location, ctx->playback.param_open.location, len+1);
+  p_seg->playback_info.pids = *p_pids;
+  p_seg->playback_info.flags = flags;
+  p_seg->playback_info.duration = p_seg->seg_info.duration;
+  list_add(p_seg, &ctx->segments);
+  DVR_WRAPPER_INFO("start to add segment %lld\n", p_seg->playback_info.segment_id);
 
-  error = dvr_playback_add_segment(ctx->playback.player, &pseg->playback_info);
+  error = dvr_playback_add_segment(ctx->playback.player, &p_seg->playback_info);
   if (error) {
-    DVR_WRAPPER_DEBUG(1, "fail to add segment %lld (%d)\n", pseg->playback_info.segment_id, error);
+    DVR_WRAPPER_INFO("fail to add segment %lld (%d)\n", p_seg->playback_info.segment_id, error);
   } else {
-    ctx->playback.status.info_full.time += pseg->seg_info.duration;
-    ctx->playback.status.info_full.size += pseg->seg_info.size;
-    ctx->playback.status.info_full.pkts += pseg->seg_info.nb_packets;
+    ctx->playback.status.info_full.time += p_seg->seg_info.duration;
+    ctx->playback.status.info_full.size += p_seg->seg_info.size;
+    ctx->playback.status.info_full.pkts += p_seg->seg_info.nb_packets;
   }
 
   return error;
@@ -802,18 +892,17 @@
 
 static int wrapper_addRecordSegment(DVR_WrapperCtx_t *ctx, DVR_RecordSegmentInfo_t *seg_info)
 {
-  DVR_WrapperRecordSegmentInfo_t *pseg;
-  int error;
+  DVR_WrapperRecordSegmentInfo_t *p_seg;
+  int error = DVR_SUCCESS;
   int sn = 0;
 
-  error = 0;
-  pseg = (DVR_WrapperRecordSegmentInfo_t *)calloc(1, sizeof(DVR_WrapperRecordSegmentInfo_t));
-  if (!pseg) {
-    error = DVR_FAILURE;
-    DVR_WRAPPER_DEBUG(1, "memory fail\n");
+  p_seg = (DVR_WrapperRecordSegmentInfo_t *)calloc(1, sizeof(DVR_WrapperRecordSegmentInfo_t));
+  if (!p_seg) {
+    DVR_WRAPPER_ERROR("memory allocation failed");
+    return DVR_FAILURE;
   }
-  pseg->info = *seg_info;
-  list_add(&pseg->head, &ctx->segments);
+  p_seg->info = *seg_info;
+  list_add(p_seg, &ctx->segments);
 
   if (ctx->record.param_open.is_timeshift ||
       (sn = ctx_isRecord_playing(ctx->record.param_open.location))) {
@@ -824,10 +913,10 @@
     else
       ctx_playback = ctx_getPlayback(sn);
 
-    DVR_WRAPPER_DEBUG(1, "ctx_playback ---- add segment\n");
+    DVR_WRAPPER_INFO("rec(sn:%ld) add_seg: playback(sn:%ld) add seg\n", ctx->sn, sn);
 
     if (ctx_playback) {
-      pthread_mutex_lock(&ctx_playback->lock);
+      wrapper_mutex_lock(&ctx_playback->wrapper_lock);
       if (ctx_valid(ctx_playback)) {
         DVR_PlaybackSegmentFlag_t flags;
 
@@ -836,16 +925,32 @@
           flags = DVR_PLAYBACK_SEGMENT_DISPLAYABLE | DVR_PLAYBACK_SEGMENT_CONTINUOUS;
           if (ctx->record.param_open.flags & DVR_RECORD_FLAG_SCRAMBLED)
             flags |= DVR_PLAYBACK_SEGMENT_ENCRYPTED;
-          wrapper_addPlaybackSegment(ctx_playback, seg_info, &ctx_playback->playback.pids_req, flags);
+          error = wrapper_addPlaybackSegment(ctx_playback, seg_info, &ctx_playback->playback.pids_req, flags);
+          if (error == DVR_FAILURE) {
+            DVR_WRAPPER_WARN("adding playback segment fails");
+          }
+        } else {
+          DVR_WRAPPER_INFO("rec(sn:%ld) add_seg: playback(sn:%ld) list empty\n", ctx->sn, sn);
         }
       } else {
-            DVR_WRAPPER_DEBUG(1, "ctx_playback ---- not valid\n");
+            DVR_WRAPPER_INFO("rec(sn:%ld) add_seg: playback(sn:%ld) not valid\n", ctx->sn, sn);
       }
-      pthread_mutex_unlock(&ctx_playback->lock);
+      wrapper_mutex_unlock(&ctx_playback->wrapper_lock);
+    }
+    else
+    {
+      DVR_WRAPPER_INFO("rec(sn:%ld) add_seg: playback(sn:%ld) not valid 2\n", ctx->sn, sn);
+    }
+
+    /*if it is not a timeshift recording, but a playing recording,
+      do not forget to obey the recording rule: link the segment!*/
+    if (!ctx->record.param_open.is_timeshift) {
+        DVR_WRAPPER_INFO("rec(sn:%ld) add_seg: update link\n", ctx->sn);
+        dvr_segment_link_op(ctx->record.param_open.location, 1, &seg_info->id, SEGMENT_OP_ADD);
     }
   } else {
-    DVR_WRAPPER_DEBUG(1, "ctx_playback -sn[%d]-\n", sn);
-    dvr_segment_link_op(ctx->record.param_open.location, 1, &seg_info->id, LSEG_OP_ADD);
+    DVR_WRAPPER_INFO("rec(sn:%ld) add_seg: update link\n", ctx->sn);
+    dvr_segment_link_op(ctx->record.param_open.location, 1, &seg_info->id, SEGMENT_OP_ADD);
   }
 
   return error;
@@ -854,59 +959,61 @@
 static int wrapper_removePlaybackSegment(DVR_WrapperCtx_t *ctx, DVR_RecordSegmentInfo_t *seg_info)
 {
   int error = -1;
-  DVR_WrapperPlaybackSegmentInfo_t *pseg = NULL, *pseg_tmp;
+  DVR_WrapperPlaybackSegmentInfo_t *p_seg = NULL, *p_seg_tmp;
+  uint32_t off_set = 0;
+  DVR_WRAPPER_INFO("timeshift, remove playback(sn:%ld) segment(%lld) ...\n", ctx->sn, seg_info->id);
 
-  DVR_WRAPPER_DEBUG(1, "timeshift, remove playback(sn:%ld) segment(%lld) ...\n", ctx->sn, seg_info->id);
-
-  list_for_each_entry_safe_reverse(pseg, pseg_tmp, &ctx->segments, head) {
-    if (pseg->seg_info.id == seg_info->id) {
+  list_for_each_entry_safe_reverse(p_seg, p_seg_tmp, &ctx->segments, head) {
+    if (p_seg->seg_info.id == seg_info->id) {
 
       if (ctx->current_segment_id == seg_info->id) {
         DVR_WrapperPlaybackSegmentInfo_t *next_seg;
 
         /*drive the player out of this will-be-deleted segment*/
-        next_seg = list_prev_entry(pseg, head);
+        next_seg = list_prev_entry(p_seg, head);
 
         if (ctx->playback.speed != 100.0f) {
           error = dvr_playback_resume(ctx->playback.player);
-          DVR_WRAPPER_DEBUG(1, "timeshift, playback(sn:%ld), resume for new start (%d)\n", ctx->sn, error);
+          DVR_WRAPPER_INFO("timeshift, playback(sn:%ld), resume for new start (%d)\n", ctx->sn, error);
         }
-
-        error = dvr_playback_seek(ctx->playback.player, next_seg->seg_info.id, 0);
-        DVR_WRAPPER_DEBUG(1, "timeshift, playback(sn:%ld), seek(seg:%llu 0) from new start (%d)\n", ctx->sn, next_seg->seg_info.id, error);
+        if (ctx->playback.param_open.vendor == DVR_PLAYBACK_VENDOR_AMAZON)
+            off_set = 10 * 1000;
+        error = dvr_playback_seek(ctx->playback.player, next_seg->seg_info.id, off_set);
+        DVR_WRAPPER_INFO("timeshift, playback(sn:%ld), seek(seg:%llu 0) from new start (%d)\n", ctx->sn, next_seg->seg_info.id, error);
 
         if (ctx->playback.speed == 0.0f) {
           error = dvr_playback_pause(ctx->playback.player, DVR_FALSE);
-          DVR_WRAPPER_DEBUG(1, "timeshift, playback(sn:%ld), keep last paused from new start (%d)\n", ctx->sn, error);
+          DVR_WRAPPER_INFO("timeshift, playback(sn:%ld), keep last paused from new start (%d)\n", ctx->sn, error);
         } else if (ctx->playback.speed != 100.0f) {
           DVR_PlaybackSpeed_t dvr_speed = {
              .speed = { ctx->playback.speed },
              .mode = ( ctx->playback.speed > 0) ? DVR_PLAYBACK_FAST_FORWARD : DVR_PLAYBACK_FAST_BACKWARD
           };
           error = dvr_playback_set_speed(ctx->playback.player, dvr_speed);
-          DVR_WRAPPER_DEBUG(1, "timeshift, playback(sn:%ld), keep last speed(x%f) from new start (%d)\n", ctx->sn,ctx->playback.speed, error);
+          DVR_WRAPPER_INFO("timeshift, playback(sn:%ld), keep last speed(x%f) from new start (%d)\n", ctx->sn,ctx->playback.speed, error);
         }
       }
 
       error = dvr_playback_remove_segment(ctx->playback.player, seg_info->id);
       if (error) {
-        /*remove playack segment fail*/
-        DVR_WRAPPER_DEBUG(1, "timeshift, playback(sn:%ld), failed to remove segment(%llu) (%d)\n", ctx->sn, seg_info->id, error);
+        /*remove playback segment fail*/
+        DVR_WRAPPER_INFO("timeshift, playback(sn:%ld), failed to remove segment(%llu) (%d)\n", ctx->sn, seg_info->id, error);
       }
 
-      list_del(&pseg->head);
+      list_del(&p_seg->head);
 
       /*record the obsolete*/
-      ctx->playback.obsolete.time += pseg->seg_info.duration;
-      ctx->playback.obsolete.size += pseg->seg_info.size;
-      ctx->playback.obsolete.pkts += pseg->seg_info.nb_packets;
+      ctx->playback.obsolete.time += p_seg->seg_info.duration;
+      ctx->playback.obsolete.size += p_seg->seg_info.size;
+      ctx->playback.obsolete.pkts += p_seg->seg_info.nb_packets;
+      DVR_WRAPPER_INFO("timeshift, remove playback(sn:%ld) segment(%lld) ..obs(%d).\n", ctx->sn, seg_info->id, ctx->playback.obsolete.time);
       dvr_playback_set_obsolete(ctx->playback.player, ctx->playback.obsolete.time);
-      free(pseg);
+      free(p_seg);
       break;
     }
   }
 
-  DVR_WRAPPER_DEBUG(1, "timeshift, remove playback(sn:%ld) segment(%lld) =(%d)\n", ctx->sn, seg_info->id, error);
+  DVR_WRAPPER_INFO("timeshift, remove playback(sn:%ld) segment(%lld) =(%d)\n", ctx->sn, seg_info->id, error);
 
   return error;
 }
@@ -914,42 +1021,62 @@
 static int wrapper_removeRecordSegment(DVR_WrapperCtx_t *ctx, DVR_WrapperRecordSegmentInfo_t *seg_info)
 {
   int error;
-  DVR_WrapperRecordSegmentInfo_t *pseg, *pseg_tmp;
+  DVR_WrapperRecordSegmentInfo_t *p_seg, *p_seg_tmp;
 
-  DVR_WRAPPER_DEBUG(1, "timeshift, remove record(sn:%ld) segment(%lld) ...\n", ctx->sn, seg_info->info.id);
+  DVR_WRAPPER_INFO("calling %s on record(sn:%ld) segment(%lld) ...",
+          __func__, ctx->sn, seg_info->info.id);
 
   /*if timeshifting, notify the playback first, then deal with record*/
   if (ctx->record.param_open.is_timeshift) {
     DVR_WrapperCtx_t *ctx_playback = ctx_getPlayback(sn_timeshift_playback);
 
     if (ctx_playback) {
-      pthread_mutex_lock(&ctx_playback->lock);
+      wrapper_mutex_lock(&ctx_playback->wrapper_lock);
+      if (ctx_playback->current_segment_id == seg_info->info.id && ctx_playback->playback.speed == 100.0f) {
+          ctx_playback->playback.tf_full = DVR_TRUE;
+          DVR_WRAPPER_INFO("%s, cannot remove record(sn:%ld) segment(%lld) for it is being"
+            " played on segment(%lld) at speed %f.", __func__, ctx->sn, seg_info->info.id,
+            ctx_playback->current_segment_id, ctx_playback->playback.speed);
+          wrapper_mutex_unlock(&ctx_playback->wrapper_lock);
+          return DVR_SUCCESS;
+      } else {
+          DVR_WRAPPER_INFO("%s, removing record(sn:%ld) segment(%lld) which is being played "
+            "on segment (%lld) at speed (%f).", __func__, ctx->sn, seg_info->info.id,
+            ctx_playback->current_segment_id,ctx_playback->playback.speed);
+      }
       if (ctx_valid(ctx_playback)
         && ctx_playback->sn == sn_timeshift_playback
         && !list_empty(&ctx_playback->segments)) {
         error = wrapper_removePlaybackSegment(ctx_playback, &seg_info->info);
+        if (error != DVR_SUCCESS) {
+          DVR_WRAPPER_ERROR("wrapper_removePlaybackSegment failed with return value %d",error);
+        }
       }
-      pthread_mutex_unlock(&ctx_playback->lock);
+      ctx_playback->playback.tf_full = DVR_FALSE;
+      wrapper_mutex_unlock(&ctx_playback->wrapper_lock);
     }
   }
 
-  list_for_each_entry_safe_reverse(pseg, pseg_tmp, &ctx->segments, head) {
-    if (pseg->info.id == seg_info->info.id) {
-      list_del(&pseg->head);
+  uint64_t id = seg_info->info.id;
+
+  list_for_each_entry_safe_reverse(p_seg, p_seg_tmp, &ctx->segments, head) {
+    if (p_seg->info.id == id) {
+      list_del(&p_seg->head);
 
       /*record the obsolete*/
-      ctx->record.obsolete.time += pseg->info.duration;
-      ctx->record.obsolete.size += pseg->info.size;
-      ctx->record.obsolete.pkts += pseg->info.nb_packets;
+      ctx->record.obsolete.time += p_seg->info.duration;
+      ctx->record.obsolete.size += p_seg->info.size;
+      ctx->record.obsolete.pkts += p_seg->info.nb_packets;
 
-      free(pseg);
+      free(p_seg);
       break;
     }
   }
 
-  error = dvr_segment_delete(ctx->record.param_open.location, seg_info->info.id);
+  error = dvr_segment_delete(ctx->record.param_open.location, id);
 
-  DVR_WRAPPER_DEBUG(1, "timeshift, remove record(sn:%ld) segment(%lld) =(%d)\n", ctx->sn, seg_info->info.id, error);
+  DVR_WRAPPER_INFO("%s, removed record(sn:%ld) segment(%lld), ret=(%d)\n",
+    __func__, ctx->sn, id, error);
 
   return error;
 }
@@ -967,9 +1094,9 @@
   ctx = ctx_getRecord(0);
   DVR_RETURN_IF_FALSE(ctx);
 
-  pthread_mutex_lock(&ctx->lock);
+  wrapper_mutex_lock(&ctx->wrapper_lock);
 
-  DVR_WRAPPER_DEBUG(1, "open record(dmx:%d) .istf(%d)..time (%ld)ms max size(%lld)byte seg size(%lld)byte\n",
+  DVR_WRAPPER_INFO("open record(dmx:%d) .is_tf(%d)..time (%ld)ms max size(%lld)byte seg size(%lld)byte\n",
   params->dmx_dev_id, params->is_timeshift, params->max_time, params->max_size, params->segment_size);
 
   ctx_reset(ctx);
@@ -1005,6 +1132,7 @@
   } else {
     open_param.notification_size = 64*1024;
   }
+  open_param.notification_time = 400;//ms
   open_param.flush_size = params->flush_size;
   open_param.ringbuf_size = params->ringbuf_size;
   open_param.event_fn = wrapper_record_event_handler;
@@ -1014,28 +1142,30 @@
     open_param.cleariv = params->cleariv;
     open_param.keylen = params->keylen;
   }
+  open_param.force_sysclock = params->force_sysclock;
+  open_param.guarded_segment_size = params->segment_size/2*3;
 
   error = dvr_record_open(&ctx->record.recorder, &open_param);
   if (error) {
-    DVR_WRAPPER_DEBUG(1, "record(dmx:%d) open fail(error:%d).\n", params->dmx_dev_id, error);
+    DVR_WRAPPER_INFO("record(dmx:%d) open fail(error:%d).\n", params->dmx_dev_id, error);
     ctx_reset(ctx);
-    pthread_mutex_unlock(&ctx->lock);
+    wrapper_mutex_unlock(&ctx->wrapper_lock);
     wrapper_releaseThreadForType(ctx->type);
     return DVR_FAILURE;
   }
   if (params->is_timeshift)
     sn_timeshift_record = ctx->sn;
 
-  DVR_WRAPPER_DEBUG(1, "record(dmx:%d) openned ok(sn:%ld).\n", params->dmx_dev_id, ctx->sn);
+  DVR_WRAPPER_INFO("record(dmx:%d) openned ok(sn:%ld).\n", params->dmx_dev_id, ctx->sn);
 
   if (params->crypto_fn) {
     error = dvr_record_set_encrypt_callback(ctx->record.recorder, params->crypto_fn, params->crypto_data);
     if (error) {
-      DVR_WRAPPER_DEBUG(1, "record(dmx:%d) set encrypt callback fail(error:%d).\n", params->dmx_dev_id, error);
+      DVR_WRAPPER_INFO("record(dmx:%d) set encrypt callback fail(error:%d).\n", params->dmx_dev_id, error);
     }
   }
 
-  pthread_mutex_unlock(&ctx->lock);
+  wrapper_mutex_unlock(&ctx->wrapper_lock);
 
   *rec = (DVR_WrapperRecord_t)ctx->sn;
   return DVR_SUCCESS;
@@ -1052,12 +1182,12 @@
   ctx = ctx_getRecord((unsigned long)rec);
   DVR_RETURN_IF_FALSE(ctx);
 
-  pthread_mutex_lock(&ctx->lock);
-  DVR_WRAPPER_DEBUG(1, "close record(sn:%ld)\n", ctx->sn);
-  DVR_RETURN_IF_FALSE_WITH_UNLOCK(ctx_valid(ctx), &ctx->lock);
+  wrapper_mutex_lock(&ctx->wrapper_lock);
+  DVR_WRAPPER_INFO("close record(sn:%ld)\n", ctx->sn);
+  WRAPPER_RETURN_IF_FALSE_WITH_UNLOCK(ctx_valid(ctx), &ctx->wrapper_lock);
 
   memset(&seg_info, 0, sizeof(seg_info));
-  error = dvr_record_stop_segment(ctx->record.recorder, &seg_info);
+  dvr_record_stop_segment(ctx->record.recorder, &seg_info);
 
   error = dvr_record_close(ctx->record.recorder);
 
@@ -1066,9 +1196,9 @@
 
   ctx_freeSegments(ctx);
 
-  DVR_WRAPPER_DEBUG(1, "record(sn:%ld) closed = (%d).\n", ctx->sn, error);
+  DVR_WRAPPER_INFO("record(sn:%ld) closed = (%d).\n", ctx->sn, error);
   ctx_reset(ctx);
-  pthread_mutex_unlock(&ctx->lock);
+  wrapper_mutex_unlock(&ctx->wrapper_lock);
 
   wrapper_releaseThreadForType(ctx->type);
 
@@ -1088,13 +1218,19 @@
   ctx = ctx_getRecord((unsigned long)rec);
   DVR_RETURN_IF_FALSE(ctx);
 
-  pthread_mutex_lock(&ctx->lock);
-  DVR_WRAPPER_DEBUG(1, "start record(sn:%ld, location:%s) save(%d)...\n", ctx->sn, ctx->record.param_open.location, params->save_rec_file);
-  DVR_RETURN_IF_FALSE_WITH_UNLOCK(ctx_valid(ctx), &ctx->lock);
+  wrapper_mutex_lock(&ctx->wrapper_lock);
+  DVR_WRAPPER_INFO("start record(sn:%ld, location:%s) save(%d)...\n", ctx->sn, ctx->record.param_open.location, params->save_rec_file);
+  WRAPPER_RETURN_IF_FALSE_WITH_UNLOCK(ctx_valid(ctx), &ctx->wrapper_lock);
 
   start_param = &ctx->record.param_start;
   memset(start_param, 0, sizeof(*start_param));
-  strncpy(start_param->location, ctx->record.param_open.location, sizeof(start_param->location));
+  const int len = strlen(ctx->record.param_open.location);
+  if (len >= DVR_MAX_LOCATION_SIZE || len <= 0) {
+    DVR_WRAPPER_ERROR("Invalid record.param_open.location length %d",len);
+    pthread_mutex_unlock(&ctx->wrapper_lock);
+    return DVR_FAILURE;
+  }
+  strncpy(start_param->location, ctx->record.param_open.location, len+1);
   start_param->segment.segment_id = ctx->record.next_segment_id++;
   start_param->segment.nb_pids = params->pids_info.nb_pids;
   for (i = 0; i < params->pids_info.nb_pids; i++) {
@@ -1119,9 +1255,9 @@
     wrapper_addRecordSegment(ctx, &new_seg_info);
   }
 
-  DVR_WRAPPER_DEBUG(1, "record(sn:%ld) started = (%d)\n", ctx->sn, error);
+  DVR_WRAPPER_INFO("record(sn:%ld) started = (%d)\n", ctx->sn, error);
 
-  pthread_mutex_unlock(&ctx->lock);
+  wrapper_mutex_unlock(&ctx->wrapper_lock);
 
   return error;
 }
@@ -1137,16 +1273,16 @@
   ctx = ctx_getRecord((unsigned long)rec);
   DVR_RETURN_IF_FALSE(ctx);
 
-  pthread_mutex_lock(&ctx->lock);
-  DVR_WRAPPER_DEBUG(1, "stop record(sn:%ld) ...\n", ctx->sn);
-  DVR_RETURN_IF_FALSE_WITH_UNLOCK(ctx_valid(ctx), &ctx->lock);
+  wrapper_mutex_lock(&ctx->wrapper_lock);
+  DVR_WRAPPER_INFO("stop record(sn:%ld) ...\n", ctx->sn);
+  WRAPPER_RETURN_IF_FALSE_WITH_UNLOCK(ctx_valid(ctx), &ctx->wrapper_lock);
 
   memset(&seg_info, 0, sizeof(seg_info));
   error = dvr_record_stop_segment(ctx->record.recorder, &seg_info);
   wrapper_updateRecordSegment(ctx, &seg_info, U_ALL);
 
-  DVR_WRAPPER_DEBUG(1, "record(sn:%ld) stopped = (%d)\n", ctx->sn, error);
-  pthread_mutex_unlock(&ctx->lock);
+  DVR_WRAPPER_INFO("record(sn:%ld) stopped = (%d)\n", ctx->sn, error);
+  wrapper_mutex_unlock(&ctx->wrapper_lock);
 
   return error;
 }
@@ -1161,14 +1297,14 @@
   ctx = ctx_getRecord((unsigned long)rec);
   DVR_RETURN_IF_FALSE(ctx);
 
-  pthread_mutex_lock(&ctx->lock);
-  DVR_WRAPPER_DEBUG(1, "pause record(sn:%ld) ...\n", ctx->sn);
-  DVR_RETURN_IF_FALSE_WITH_UNLOCK(ctx_valid(ctx), &ctx->lock);
+  wrapper_mutex_lock(&ctx->wrapper_lock);
+  DVR_WRAPPER_INFO("pause record(sn:%ld) ...\n", ctx->sn);
+  WRAPPER_RETURN_IF_FALSE_WITH_UNLOCK(ctx_valid(ctx), &ctx->wrapper_lock);
 
   error = dvr_record_pause(ctx->record.recorder);
 
-  DVR_WRAPPER_DEBUG(1, "record(sn:%ld) pauseed = (%d)\n", ctx->sn, error);
-  pthread_mutex_unlock(&ctx->lock);
+  DVR_WRAPPER_INFO("record(sn:%ld) pauseed = (%d)\n", ctx->sn, error);
+  wrapper_mutex_unlock(&ctx->wrapper_lock);
 
   return error;
 }
@@ -1183,23 +1319,108 @@
   ctx = ctx_getRecord((unsigned long)rec);
   DVR_RETURN_IF_FALSE(ctx);
 
-  pthread_mutex_lock(&ctx->lock);
-  DVR_WRAPPER_DEBUG(1, "resume record(sn:%ld) ...\n", ctx->sn);
-  DVR_RETURN_IF_FALSE_WITH_UNLOCK(ctx_valid(ctx), &ctx->lock);
+  wrapper_mutex_lock(&ctx->wrapper_lock);
+  DVR_WRAPPER_INFO("resume record(sn:%ld) ...\n", ctx->sn);
+  WRAPPER_RETURN_IF_FALSE_WITH_UNLOCK(ctx_valid(ctx), &ctx->wrapper_lock);
 
   error = dvr_record_resume(ctx->record.recorder);
 
-  DVR_WRAPPER_DEBUG(1, "record(sn:%ld) resumed = (%d)\n", ctx->sn, error);
-  pthread_mutex_unlock(&ctx->lock);
+  DVR_WRAPPER_INFO("record(sn:%ld) resumed = (%d)\n", ctx->sn, error);
+  wrapper_mutex_unlock(&ctx->wrapper_lock);
 
   return error;
 }
 
+/* Return true if arr1 contains all elements in arr2 */
+static DVR_Bool_t pids_test_include(
+                  DVR_StreamPid_t* arr1, DVR_RecordPidAction_t *act1, int size1,
+                  DVR_StreamPid_t* arr2, DVR_RecordPidAction_t *act2, int size2)
+{
+  DVR_Bool_t ret = DVR_TRUE;
+  for (int i=0;i<size2;i++)
+  { // iterate all elements in arr2 to check if they exist in arr1
+    DVR_Bool_t found=DVR_FALSE;
+
+    if (act2[i] == DVR_RECORD_PID_CLOSE)
+      continue;
+
+    for (int j=0;j<size1;j++)
+    {
+      if (act1[j] != DVR_RECORD_PID_CLOSE
+          && arr2[i].pid == arr1[j].pid)
+      {
+        found=DVR_TRUE;
+        break;
+      }
+    }
+    if (found == DVR_FALSE)
+    {
+      ret=DVR_FALSE;
+      break;
+    }
+  }
+  return ret;
+}
+
+static DVR_Bool_t pids_equal(const DVR_RecordSegmentStartParams_t* p1,
+                             const DVR_WrapperUpdatePidsParams_t* p2)
+{
+  int i=0;
+  char buf[128]={0};
+  int cnt=0;
+  int chars=0;
+
+  DVR_RETURN_IF_FALSE(p1 != NULL && p2 != NULL);
+  DVR_RETURN_IF_FALSE(p1->nb_pids>0 && p2->nb_pids>0);
+
+  DVR_Bool_t cond1 = pids_test_include(p1->pids,p1->pid_action,p1->nb_pids,
+                        p2->pids,p2->pid_action,p2->nb_pids);
+  DVR_Bool_t cond2 = pids_test_include(p2->pids,p2->pid_action,p2->nb_pids,
+                        p1->pids,p1->pid_action,p1->nb_pids);
+  DVR_Bool_t is_equal = (cond1 && cond2);
+  int removed;
+
+  removed = 0;
+  for (i=0;i<p1->nb_pids;i++)
+  {
+    if (p1->pid_action[i] == DVR_RECORD_PID_CLOSE) {
+      removed++;
+      continue;
+    }
+    chars = snprintf(buf+cnt,sizeof(buf)-cnt,"0x%hx,",p1->pids[i].pid);
+    if (chars<0)
+    {
+      break;
+    }
+    cnt += chars;
+  }
+  DVR_INFO("%s nb_pids1:%d, pids1: %s",__func__,p1->nb_pids-removed,buf);
+  memset(buf,0,sizeof(buf));
+
+  removed = 0;
+  for (i=0,cnt=0;i<p2->nb_pids;i++)
+  {
+    if (p2->pid_action[i] == DVR_RECORD_PID_CLOSE) {
+      removed++;
+      continue;
+    }
+    chars = snprintf(buf+cnt,sizeof(buf)-cnt,"0x%hx,",p2->pids[i].pid);
+    if (chars<0)
+    {
+      break;
+    }
+    cnt += chars;
+  }
+  DVR_INFO("%s nb_pids2:%d, pids2: %s",__func__,p2->nb_pids-removed,buf);
+  DVR_INFO("%s is_equal:%d",__func__,is_equal);
+  return is_equal;
+}
+
 int dvr_wrapper_update_record_pids (DVR_WrapperRecord_t rec, DVR_WrapperUpdatePidsParams_t *params)
 {
   DVR_WrapperCtx_t *ctx;
   DVR_RecordStartParams_t *start_param;
-  DVR_RecordSegmentInfo_t seg_info;;
+  DVR_RecordSegmentInfo_t seg_info;
   int i;
   int error;
 
@@ -1209,13 +1430,25 @@
   ctx = ctx_getRecord((unsigned long)rec);
   DVR_RETURN_IF_FALSE(ctx);
 
-  pthread_mutex_lock(&ctx->lock);
-  DVR_WRAPPER_DEBUG(1, "update record(sn:%ld)\n", ctx->sn);
-  DVR_RETURN_IF_FALSE_WITH_UNLOCK(ctx_valid(ctx), &ctx->lock);
+  wrapper_mutex_lock(&ctx->wrapper_lock);
+  DVR_WRAPPER_INFO("update record(sn:%ld)\n", ctx->sn);
+  WRAPPER_RETURN_IF_FALSE_WITH_UNLOCK(ctx_valid(ctx), &ctx->wrapper_lock);
 
   start_param = &ctx->record.param_update;
+  if (pids_equal(&(start_param->segment),params))
+  {
+    wrapper_mutex_unlock(&ctx->wrapper_lock);
+    return DVR_TRUE;
+  }
+
   memset(start_param, 0, sizeof(*start_param));
-  strncpy(start_param->location, ctx->record.param_open.location, sizeof(start_param->location));
+  const int len = strlen(ctx->record.param_open.location);
+  if (len >= DVR_MAX_LOCATION_SIZE || len <= 0) {
+    DVR_WRAPPER_ERROR("Invalid record.param_open.location length %d",len);
+    pthread_mutex_unlock(&ctx->wrapper_lock);
+    return DVR_FAILURE;
+  }
+  strncpy(start_param->location, ctx->record.param_open.location, len+1);
   start_param->segment.segment_id = ctx->record.next_segment_id++;
   start_param->segment.nb_pids = params->nb_pids;
   for (i = 0; i < params->nb_pids; i++) {
@@ -1230,8 +1463,8 @@
     wrapper_addRecordSegment(ctx, &new_seg_info);
   }
 
-  DVR_WRAPPER_DEBUG(1, "record(sn:%ld) updated = (%d)\n", ctx->sn, error);
-  pthread_mutex_unlock(&ctx->lock);
+  DVR_WRAPPER_INFO("record(sn:%ld) updated = (%d)\n", ctx->sn, error);
+  wrapper_mutex_unlock(&ctx->wrapper_lock);
 
   return error;
 }
@@ -1248,14 +1481,14 @@
   ctx = ctx_getRecord((unsigned long)rec);
   DVR_RETURN_IF_FALSE(ctx);
 
-  pthread_mutex_lock(&ctx->lock);
+  wrapper_mutex_lock(&ctx->wrapper_lock);
 
-  DVR_WRAPPER_DEBUG(1, "get record(sn:%ld) status ...\n", ctx->sn);
-  DVR_RETURN_IF_FALSE_WITH_UNLOCK(ctx_valid(ctx), &ctx->lock);
+  DVR_WRAPPER_INFO("get record(sn:%ld) status ...\n", ctx->sn);
+  WRAPPER_RETURN_IF_FALSE_WITH_UNLOCK(ctx_valid(ctx), &ctx->wrapper_lock);
 
   error = process_generateRecordStatus(ctx, &s);
 
-  DVR_WRAPPER_DEBUG(1, "record(sn:%ld) state/time/size/pkts(%d/%ld/%lld/%u) (%d)\n",
+  DVR_WRAPPER_INFO("record(sn:%ld) state/time/size/pkts(%d/%ld/%lld/%u) (%d)\n",
     ctx->sn,
     s.state,
     s.info.time,
@@ -1265,7 +1498,7 @@
 
   *status = s;
 
-  pthread_mutex_unlock(&ctx->lock);
+  wrapper_mutex_unlock(&ctx->wrapper_lock);
 
   return error;
 }
@@ -1280,9 +1513,9 @@
   ctx = ctx_getRecord((unsigned long)rec);
   DVR_RETURN_IF_FALSE(ctx);
 
-  pthread_mutex_lock(&ctx->lock);
+  wrapper_mutex_lock(&ctx->wrapper_lock);
   error = dvr_record_is_secure_mode(ctx->record.recorder);
-  pthread_mutex_unlock(&ctx->lock);
+  wrapper_mutex_unlock(&ctx->wrapper_lock);
   return error;
 }
 
@@ -1297,9 +1530,9 @@
   ctx = ctx_getRecord((unsigned long)rec);
   DVR_RETURN_IF_FALSE(ctx);
 
-  pthread_mutex_lock(&ctx->lock);
+  wrapper_mutex_lock(&ctx->wrapper_lock);
   error = dvr_record_set_secure_buffer(ctx->record.recorder, p_secure_buf, len);
-  pthread_mutex_unlock(&ctx->lock);
+  wrapper_mutex_unlock(&ctx->wrapper_lock);
   return error;
 }
 
@@ -1314,9 +1547,9 @@
   ctx = ctx_getRecord((unsigned long)rec);
   DVR_RETURN_IF_FALSE(ctx);
 
-  pthread_mutex_lock(&ctx->lock);
+  wrapper_mutex_lock(&ctx->wrapper_lock);
   error = dvr_record_set_encrypt_callback(ctx->record.recorder, func, userdata);
-  pthread_mutex_unlock(&ctx->lock);
+  wrapper_mutex_unlock(&ctx->wrapper_lock);
   return error;
 }
 
@@ -1335,9 +1568,9 @@
   ctx = ctx_getPlayback(0);
   DVR_RETURN_IF_FALSE(ctx);
 
-  pthread_mutex_lock(&ctx->lock);
+  wrapper_mutex_lock(&ctx->wrapper_lock);
 
-  DVR_WRAPPER_DEBUG(1, "open playback(dmx:%d) ..vendor[%d]params->block_size[%d].\n", params->dmx_dev_id, params->vendor, params->block_size);
+  DVR_WRAPPER_INFO("open playback(dmx:%d) ..vendor[%d]params->block_size[%d].\n", params->dmx_dev_id, params->vendor, params->block_size);
 
   ctx_reset(ctx);
 
@@ -1370,21 +1603,21 @@
 
   error = dvr_playback_open(&ctx->playback.player, &open_param);
   if (error) {
-    DVR_WRAPPER_DEBUG(1, "playback(dmx:%d) openned fail(error:%d).\n", params->dmx_dev_id, error);
+    DVR_WRAPPER_INFO("playback(dmx:%d) openned fail(error:%d).\n", params->dmx_dev_id, error);
     ctx_reset(ctx);
-    pthread_mutex_unlock(&ctx->lock);
+    wrapper_mutex_unlock(&ctx->wrapper_lock);
     wrapper_releaseThreadForType(ctx->type);
     return DVR_FAILURE;
   }
   if (params->is_timeshift)
     sn_timeshift_playback = ctx->sn;
 
-  DVR_WRAPPER_DEBUG(1, "hanyh: playback(dmx:%d) openned ok(sn:%ld).\n", params->dmx_dev_id, ctx->sn);
+  DVR_WRAPPER_INFO("playback(dmx:%d) openned ok(sn:%ld).\n", params->dmx_dev_id, ctx->sn);
   error = dvr_playback_set_decrypt_callback(ctx->playback.player, params->crypto_fn, params->crypto_data);
   if (error) {
-    DVR_WRAPPER_DEBUG(1, "playback set deccrypt callback fail(error:%d).\n", error);
+    DVR_WRAPPER_INFO("playback set decrypt callback fail(error:%d).\n", error);
   }
-  pthread_mutex_unlock(&ctx->lock);
+  wrapper_mutex_unlock(&ctx->wrapper_lock);
 
   *playback = (DVR_WrapperPlayback_t)ctx->sn;
   return DVR_SUCCESS;
@@ -1400,33 +1633,37 @@
   ctx = ctx_getPlayback((unsigned long)playback);
   DVR_RETURN_IF_FALSE(ctx);
 
-  pthread_mutex_lock(&ctx->lock);
-  DVR_WRAPPER_DEBUG(1, "close playback(sn:%ld)\n", ctx->sn);
-  DVR_RETURN_IF_FALSE_WITH_UNLOCK(ctx_valid(ctx), &ctx->lock);
+  wrapper_mutex_lock(&ctx->wrapper_lock);
+  DVR_WRAPPER_INFO("close playback(sn:%ld)\n", ctx->sn);
+  WRAPPER_RETURN_IF_FALSE_WITH_UNLOCK(ctx_valid(ctx), &ctx->wrapper_lock);
 
   if (ctx->playback.param_open.is_timeshift)
     sn_timeshift_playback = 0;
 
   /*try stop first*/
-  error = dvr_playback_stop(ctx->playback.player, DVR_TRUE);
+  dvr_playback_stop(ctx->playback.player, DVR_TRUE);
 
   {
     /*remove all segments*/
-    DVR_WrapperPlaybackSegmentInfo_t *pseg;
+    DVR_WrapperPlaybackSegmentInfo_t *p_seg;
 
-    list_for_each_entry(pseg, &ctx->segments, head) {
-      error = dvr_playback_remove_segment(ctx->playback.player, pseg->playback_info.segment_id);
-      DVR_WRAPPER_DEBUG(1, "playback(sn:%ld) remove seg(%lld) (%d)\n",
-        ctx->sn, pseg->playback_info.segment_id, error);
+    // This error is suppressed as the macro code is picked from kernel.
+    // prefetch() here incurring self_assign is used to avoid some compiling
+    // warnings.
+    // coverity[self_assign]
+    list_for_each_entry(p_seg, &ctx->segments, head) {
+      error = dvr_playback_remove_segment(ctx->playback.player, p_seg->playback_info.segment_id);
+      DVR_WRAPPER_INFO("playback(sn:%ld) remove seg(%lld) (%d)\n",
+        ctx->sn, p_seg->playback_info.segment_id, error);
     }
     ctx_freeSegments(ctx);
   }
 
   error = dvr_playback_close(ctx->playback.player);
 
-  DVR_WRAPPER_DEBUG(1, "playback(sn:%ld) closed.\n", ctx->sn);
+  DVR_WRAPPER_INFO("playback(sn:%ld) closed.\n", ctx->sn);
   ctx_reset(ctx);
-  pthread_mutex_unlock(&ctx->lock);
+  wrapper_mutex_unlock(&ctx->wrapper_lock);
 
   wrapper_releaseThreadForType(ctx->type);
 
@@ -1436,14 +1673,15 @@
 int dvr_wrapper_start_playback (DVR_WrapperPlayback_t playback, DVR_PlaybackFlag_t flags, DVR_PlaybackPids_t *p_pids)
 {
   DVR_WrapperCtx_t *ctx;
-  int error;
+  int error=0;
   uint64_t *p_segment_ids;
   uint32_t segment_nb;
   uint32_t i;
   DVR_RecordSegmentInfo_t seg_info_1st;
-  int got_1st_seg;
+  int got_1st_seg=0;
   DVR_WrapperCtx_t *ctx_record;/*for timeshift*/
   DVR_Bool_t is_timeshift = DVR_FALSE;
+  DVR_PlaybackSegmentFlag_t seg_flags = 0;
 
   DVR_RETURN_IF_FALSE(playback);
   DVR_RETURN_IF_FALSE(p_pids);
@@ -1454,11 +1692,11 @@
   ctx_record = ctx_getRecord(sn_timeshift_record);
 
   if (ctx_record) {
-    pthread_mutex_lock(&ctx_record->lock);
+    wrapper_mutex_lock(&ctx_record->wrapper_lock);
     if (!ctx_valid(ctx_record)
       || ctx_record->sn != sn_timeshift_record) {
-      DVR_WRAPPER_DEBUG(1, "timeshift, record is not for timeshifting, FATAL error found\n");
-      pthread_mutex_unlock(&ctx_record->lock);
+      DVR_WRAPPER_INFO("timeshift, record is not for timeshifting, FATAL error found\n");
+      wrapper_mutex_unlock(&ctx_record->wrapper_lock);
       is_timeshift  = DVR_FALSE;
     } else {
       is_timeshift  = DVR_TRUE;
@@ -1468,9 +1706,9 @@
   ctx = ctx_getPlayback((unsigned long)playback);
   DVR_RETURN_IF_FALSE(ctx);
 
-  pthread_mutex_lock(&ctx->lock);
+  wrapper_mutex_lock(&ctx->wrapper_lock);
 
-  DVR_WRAPPER_DEBUG(1, "start playback(sn:%ld) (%s)\n\t flags(0x%x) v/a/ad/sub/pcr(%d:%d %d:%d %d:%d %d:%d %d)\n",
+  DVR_WRAPPER_INFO("start playback(sn:%ld) (%s)\n\t flags(0x%x) v/a/ad/sub/pcr(%d:%d %d:%d %d:%d %d:%d %d)\n",
     ctx->sn,
     ctx->playback.param_open.location,
     flags,
@@ -1480,16 +1718,16 @@
     p_pids->subtitle.pid, p_pids->subtitle.format,
     p_pids->pcr.pid);
 
-  DVR_RETURN_IF_FALSE_WITH_UNLOCK(ctx_valid(ctx), &ctx->lock);
+  WRAPPER_RETURN_IF_FALSE_WITH_UNLOCK(ctx_valid(ctx), &ctx->wrapper_lock);
 
   if (ctx->playback.param_open.is_timeshift) {
     /*lock the recorder to avoid changing the recording segments*/
     if (is_timeshift == DVR_FALSE) {
-      DVR_WRAPPER_DEBUG(1, "timeshift, record is not for timeshifting, FATAL error return\n");
-      pthread_mutex_unlock(&ctx->lock);
+      DVR_WRAPPER_INFO("timeshift, record is not for timeshifting, FATAL error return\n");
+      wrapper_mutex_unlock(&ctx->wrapper_lock);
       return DVR_FAILURE;
     } else {
-      DVR_WRAPPER_DEBUG(1, "playback(sn:%ld) record(sn:%ld) locked ok due to timeshift\n",
+      DVR_WRAPPER_INFO("playback(sn:%ld) record(sn:%ld) locked ok due to timeshift\n",
         ctx->sn, ctx_record->sn);
     }
   }
@@ -1500,68 +1738,211 @@
   error = dvr_segment_get_list(ctx->playback.param_open.location, &segment_nb, &p_segment_ids);
   if (!error) {
     got_1st_seg = 0;
-    DVR_WRAPPER_DEBUG(1, "get list segment_nb::%d",segment_nb);
-    for (i = 0; i < segment_nb; i++) {
-      DVR_RecordSegmentInfo_t seg_info;
-      DVR_PlaybackSegmentFlag_t flags;
+    struct list_head           info_list;         /**< segment list head*/
+    INIT_LIST_HEAD(&info_list);
 
-      error = dvr_segment_get_info(ctx->playback.param_open.location, p_segment_ids[i], &seg_info);
-      if (error) {
-        error = DVR_FAILURE;
-        DVR_WRAPPER_DEBUG(1, "fail to get seg info (location:%s, seg:%llu), (error:%d)\n",
-          ctx->playback.param_open.location, p_segment_ids[i], error);
-        break;
-      }
-      //add check if has audio  or video pid. if not exist. not add segment to playback
-      int ii = 0;
-      int has_av = 0;
-      for (ii = 0; ii < seg_info.nb_pids; ii++) {
-        int type = (seg_info.pids[ii].type >> 24) & 0x0f;
-        if (type == DVR_STREAM_TYPE_VIDEO ||
-          type == DVR_STREAM_TYPE_AUDIO ||
-          type == DVR_STREAM_TYPE_AD) {
-         DVR_WRAPPER_DEBUG(1, "success to get seg av info \n");
-          DVR_WRAPPER_DEBUG(1, "success to get seg av info type[0x%x][%d] [%d][%d][%d]\n",(seg_info.pids[ii].type >> 24)&0x0f,seg_info.pids[ii].pid,
-          DVR_STREAM_TYPE_VIDEO,
-          DVR_STREAM_TYPE_AUDIO,
-          DVR_STREAM_TYPE_AD);
-          has_av = 1;
-          //break;
-        } else {
-          DVR_WRAPPER_DEBUG(1, "error to get seg av info type[0x%x][%d] [%d][%d][%d]\n",(seg_info.pids[ii].type >> 24)&0x0f,seg_info.pids[ii].pid,
-          DVR_STREAM_TYPE_VIDEO,
-          DVR_STREAM_TYPE_AUDIO,
-          DVR_STREAM_TYPE_AD);
+    DVR_WRAPPER_INFO("get list segment_nb::%d",segment_nb);
+    //we need free info list buf when we used end.
+    error = dvr_segment_get_allInfo(ctx->playback.param_open.location, &info_list);
+    if (error == DVR_FAILURE) {
+          error = DVR_FAILURE;
+          DVR_WRAPPER_INFO("fail to get all seg info (location:%s), (error:%d)\n",
+            ctx->playback.param_open.location, error);
+          // Tainted data issue originating from fgets seem false positive, so we
+          // just suppress it here.
+          // coverity[tainted_data]
+          for (i = 0; i < segment_nb; i++) {
+            DVR_RecordSegmentInfo_t seg_info;
+            memset((void*)&seg_info,0,sizeof(seg_info));
+
+            error = dvr_segment_get_info(ctx->playback.param_open.location, p_segment_ids[i], &seg_info);
+            if (error) {
+              error = DVR_FAILURE;
+              DVR_WRAPPER_INFO("fail to get seg info (location:%s, seg:%llu), (error:%d)\n",
+                ctx->playback.param_open.location, p_segment_ids[i], error);
+              break;
+            }
+            //add check if has audio  or video pid. if not exist. not add segment to playback
+            int ii = 0;
+            int has_av = 0;
+            // Tainted data issue originating from fgets seem false positive, so we
+            // just suppress it here.
+            // coverity[tainted_data]
+            for (ii = 0; ii < seg_info.nb_pids; ii++) {
+              int type = (seg_info.pids[ii].type >> 24) & 0x0f;
+              if (type == DVR_STREAM_TYPE_VIDEO ||
+                type == DVR_STREAM_TYPE_AUDIO ||
+                type == DVR_STREAM_TYPE_AD) {
+              DVR_WRAPPER_INFO("success to get seg av info \n");
+                DVR_WRAPPER_INFO("success to get seg av info type[0x%x][%d] [%d][%d][%d]\n",(seg_info.pids[ii].type >> 24)&0x0f,seg_info.pids[ii].pid,
+                DVR_STREAM_TYPE_VIDEO,
+                DVR_STREAM_TYPE_AUDIO,
+                DVR_STREAM_TYPE_AD);
+                has_av = 1;
+                //break;
+              } else {
+                DVR_WRAPPER_INFO("error to get seg av info type[0x%x][%d] [%d][%d][%d]\n",(seg_info.pids[ii].type >> 24)&0x0f,seg_info.pids[ii].pid,
+                DVR_STREAM_TYPE_VIDEO,
+                DVR_STREAM_TYPE_AUDIO,
+                DVR_STREAM_TYPE_AD);
+              }
+            }
+            if (has_av == 0) {
+              DVR_WRAPPER_INFO("fail to get seg av info \n");
+              continue;
+            } else {
+              DVR_WRAPPER_INFO("success to get seg av info \n");
+            }
+            seg_flags = DVR_PLAYBACK_SEGMENT_DISPLAYABLE | DVR_PLAYBACK_SEGMENT_CONTINUOUS;
+            error = wrapper_addPlaybackSegment(ctx, &seg_info, p_pids, seg_flags);
+            if (error == DVR_FAILURE) {
+              DVR_WRAPPER_WARN("adding playback segment fails");
+              break;
+            }
+            /*copy the 1st segment*/
+            if (got_1st_seg == 0) {
+                seg_info_1st = seg_info;
+                got_1st_seg = 1;
+            }
+          }
+    } else {
+        // Tainted data issue originating from fgets seem false positive, so we
+        // just suppress it here.
+        // coverity[tainted_data]
+        for (i = 0; i < segment_nb; i++) {
+          DVR_RecordSegmentInfo_t *p_seg_info;
+          int found = 0;
+          // This error is suppressed as the macro code is picked from kernel.
+          // prefetch() here incurring self_assign is used to avoid some compiling
+          // warnings.
+          // coverity[self_assign]
+          list_for_each_entry(p_seg_info, &info_list, head)
+          {
+            if (p_seg_info->id == p_segment_ids[i]) {
+              found = 1;
+              DVR_WRAPPER_INFO("get segment info::%d", i);
+              break;
+            }
+          }
+          if (!found) {
+            //last info is not found if when recording occured power off.
+            if (p_segment_ids[i] == segment_nb - 1) {
+              DVR_RecordSegmentInfo_t seg_info;
+              memset((void*)&seg_info,0,sizeof(seg_info));
+
+              error = dvr_segment_get_info(ctx->playback.param_open.location, p_segment_ids[i], &seg_info);
+              if (error) {
+                error = DVR_FAILURE;
+                DVR_WRAPPER_INFO("fail to get seg info (location:%s, seg:%llu), (error:%d)\n",
+                  ctx->playback.param_open.location, p_segment_ids[i], error);
+                break;
+              }
+              //
+              //add check if has audio  or video pid. if not exist. not add segment to playback
+              int ii = 0;
+              int has_av = 0;
+              // Tainted data issue originating from fgets seem false positive, so we
+              // just suppress it here.
+              // coverity[tainted_data]
+              for (ii = 0; ii < seg_info.nb_pids; ii++) {
+                int type = (seg_info.pids[ii].type >> 24) & 0x0f;
+                if (type == DVR_STREAM_TYPE_VIDEO ||
+                  type == DVR_STREAM_TYPE_AUDIO ||
+                  type == DVR_STREAM_TYPE_AD) {
+                DVR_WRAPPER_INFO("success to get seg av info \n");
+                  DVR_WRAPPER_INFO("success to get seg av info type[0x%x][%d] [%d][%d][%d]\n",(seg_info.pids[ii].type >> 24)&0x0f,seg_info.pids[ii].pid,
+                  DVR_STREAM_TYPE_VIDEO,
+                  DVR_STREAM_TYPE_AUDIO,
+                  DVR_STREAM_TYPE_AD);
+                  has_av = 1;
+                  //break;
+                } else {
+                  DVR_WRAPPER_INFO("error to get seg av info type[0x%x][%d] [%d][%d][%d]\n",(seg_info.pids[ii].type >> 24)&0x0f,seg_info.pids[ii].pid,
+                  DVR_STREAM_TYPE_VIDEO,
+                  DVR_STREAM_TYPE_AUDIO,
+                  DVR_STREAM_TYPE_AD);
+                }
+              }
+              if (has_av == 0) {
+                DVR_WRAPPER_INFO("fail to get seg av info \n");
+                continue;
+              } else {
+                DVR_WRAPPER_INFO("success to get seg av info \n");
+              }
+              seg_flags = DVR_PLAYBACK_SEGMENT_DISPLAYABLE | DVR_PLAYBACK_SEGMENT_CONTINUOUS;
+              error = wrapper_addPlaybackSegment(ctx, &seg_info, p_pids, seg_flags);
+              if (error == DVR_FAILURE) {
+                DVR_WRAPPER_WARN("adding playback segment fails");
+                break;
+              }
+            }
+            continue;
+          }
+
+          //add check if has audio  or video pid. if not exist. not add segment to playback
+          int ii = 0;
+          int has_av = 0;
+          for (ii = 0; ii < p_seg_info->nb_pids; ii++) {
+            int type = (p_seg_info->pids[ii].type >> 24) & 0x0f;
+            if (type == DVR_STREAM_TYPE_VIDEO ||
+              type == DVR_STREAM_TYPE_AUDIO ||
+              type == DVR_STREAM_TYPE_AD) {
+            DVR_WRAPPER_INFO("success to get seg av info \n");
+              DVR_WRAPPER_INFO("success to get seg av info type[0x%x][%d] [%d][%d][%d]\n",(p_seg_info->pids[ii].type >> 24)&0x0f,p_seg_info->pids[ii].pid,
+              DVR_STREAM_TYPE_VIDEO,
+              DVR_STREAM_TYPE_AUDIO,
+              DVR_STREAM_TYPE_AD);
+              has_av = 1;
+              //break;
+            } else {
+              DVR_WRAPPER_INFO("error to get seg av info type[0x%x][%d] [%d][%d][%d]\n",(p_seg_info->pids[ii].type >> 24)&0x0f,p_seg_info->pids[ii].pid,
+              DVR_STREAM_TYPE_VIDEO,
+              DVR_STREAM_TYPE_AUDIO,
+              DVR_STREAM_TYPE_AD);
+            }
+          }
+          if (has_av == 0) {
+            DVR_WRAPPER_INFO("fail to get seg av info \n");
+            continue;
+          } else {
+            DVR_WRAPPER_INFO("success to get seg av info \n");
+          }
+          seg_flags = DVR_PLAYBACK_SEGMENT_DISPLAYABLE | DVR_PLAYBACK_SEGMENT_CONTINUOUS;
+          error = wrapper_addPlaybackSegment(ctx, p_seg_info, p_pids, seg_flags);
+          if (error == DVR_FAILURE) {
+            DVR_WRAPPER_WARN("adding playback segment fails");
+            break;
+          }
+
+          /*copy the 1st segment*/
+          if (got_1st_seg == 0) {
+              seg_info_1st = *p_seg_info;
+              got_1st_seg = 1;
+          }
         }
-      }
-      if (has_av == 0) {
-        DVR_WRAPPER_DEBUG(1, "fail to get seg av info \n");
-        continue;
-      } else {
-        DVR_WRAPPER_DEBUG(1, "success to get seg av info \n");
-      }
-      flags = DVR_PLAYBACK_SEGMENT_DISPLAYABLE | DVR_PLAYBACK_SEGMENT_CONTINUOUS;
-      error = wrapper_addPlaybackSegment(ctx, &seg_info, p_pids, flags);
-      if (error)
-        break;
-
-      /*copy the 1st segment*/
-      if (got_1st_seg == 0) {
-          seg_info_1st = seg_info;
-          got_1st_seg = 1;
-      }
+        //free list
+        DVR_RecordSegmentInfo_t *segment = NULL;
+        DVR_RecordSegmentInfo_t *segment_tmp = NULL;
+        list_for_each_entry_safe(segment, segment_tmp, &info_list, head)
+        {
+            if (segment) {
+              list_del(&segment->head);
+              free(segment);
+            }
+        }
     }
+
     free(p_segment_ids);
 
     /* return if no segment or fail to add */
     if (!error && got_1st_seg) {
 
-      /*copy the obsolete infomation, must for timeshifting*/
+      /*copy the obsolete information, must for timeshifting*/
       if (ctx->playback.param_open.is_timeshift && ctx_record) {
         ctx->playback.obsolete = ctx_record->record.obsolete;
       }
 
-      DVR_WRAPPER_DEBUG(1, "playback(sn:%ld) (%d) segments added\n", ctx->sn, i);
+      DVR_WRAPPER_INFO("playback(sn:%ld) (%d) segments added\n", ctx->sn, i);
 
       ctx->playback.reach_end = DVR_FALSE;
       if ((flags&DVR_PLAYBACK_STARTED_PAUSEDLIVE) == DVR_PLAYBACK_STARTED_PAUSEDLIVE)
@@ -1570,34 +1951,147 @@
         ctx->playback.speed = 100.0f;
 
       ctx->playback.pids_req = *p_pids;
-      //calualte segment id and pos
+      //calculate segment id and pos
       if (dvr_playback_check_limit(ctx->playback.player)) {
-        pthread_mutex_unlock(&ctx->lock);
+        wrapper_mutex_unlock(&ctx->wrapper_lock);
         dvr_wrapper_seek_playback(playback, 0);
-        pthread_mutex_lock(&ctx->lock);
+        wrapper_mutex_lock(&ctx->wrapper_lock);
         error = dvr_playback_start(ctx->playback.player, flags);
       } else {
-        error = dvr_playback_seek(ctx->playback.player, seg_info_1st.id, 0);
+        dvr_playback_seek(ctx->playback.player, seg_info_1st.id, 0);
         error = dvr_playback_start(ctx->playback.player, flags);
-        DVR_WRAPPER_DEBUG(1, "playback(sn:%ld) seek(seg:%llu 0) for start (%d)\n",
+        DVR_WRAPPER_INFO("playback(sn:%ld) seek(seg:%llu 0) for start (%d)\n",
           ctx->sn, seg_info_1st.id, error);
       }
-      DVR_WRAPPER_DEBUG(1, "playback(sn:%ld) started (%d)\n", ctx->sn, error);
+      DVR_WRAPPER_INFO("playback(sn:%ld) started (%d)\n", ctx->sn, error);
+    } else {
+      DVR_WRAPPER_INFO("playback(sn:%ld) started (%d)got_1st_seg:%d\n", ctx->sn, error, got_1st_seg);
     }
   }
 
   if (ctx->playback.param_open.is_timeshift) {
     /*unlock the recorder locked above*/
     if (ctx_record && ctx_valid(ctx_record)) {
-        pthread_mutex_unlock(&ctx_record->lock);
-        DVR_WRAPPER_DEBUG(1, "playback(sn:%ld), record(sn:%ld) unlocked ok due to timeshift\n",
+        wrapper_mutex_unlock(&ctx_record->wrapper_lock);
+        DVR_WRAPPER_INFO("playback(sn:%ld), record(sn:%ld) unlocked ok due to timeshift\n",
           ctx->sn, ctx_record->sn);
     }
   }
-  pthread_mutex_unlock(&ctx->lock);
+  wrapper_mutex_unlock(&ctx->wrapper_lock);
 
   return error;
 }
+//stop record and playback
+int dvr_wrapper_stop_timeshift (DVR_WrapperPlayback_t playback)
+{
+  DVR_WrapperCtx_t *ctx_record = NULL;/*for timeshift*/
+  int error;
+  DVR_WRAPPER_INFO("stop timeshift record\n");
+
+  //stop timeshift record
+  ctx_record = ctx_getRecord(sn_timeshift_record);
+  dvr_wrapper_stop_record((DVR_WrapperRecord_t)sn_timeshift_record);
+
+  DVR_WRAPPER_INFO("stop timeshift ...stop play\n");
+  //stop play
+  error = dvr_wrapper_stop_playback(playback);
+  //del timeshift file
+  if (ctx_record != NULL) {
+    DVR_WRAPPER_INFO("del timeshift(sn:%ld) ...3\n", ctx_record->sn);
+    error = dvr_segment_del_by_location(ctx_record->record.param_open.location);
+  }
+  return error;
+}
+//start record and start playback
+int dvr_wrapper_restart_timeshift(DVR_WrapperPlayback_t playback, DVR_PlaybackFlag_t flags, DVR_PlaybackPids_t *p_pids)
+{
+  DVR_WrapperCtx_t *ctx;
+  DVR_RecordStartParams_t *start_param;
+  int error;
+
+  ctx = ctx_getRecord((unsigned long)sn_timeshift_record);
+  DVR_RETURN_IF_FALSE(ctx);
+
+  wrapper_mutex_lock(&ctx->wrapper_lock);
+  DVR_WRAPPER_INFO("restart record(sn:%ld, location:%s)...\n", ctx->sn, ctx->record.param_open.location);
+  WRAPPER_RETURN_IF_FALSE_WITH_UNLOCK(ctx_valid(ctx), &ctx->wrapper_lock);
+
+  {
+    //clear old record status
+    //   struct {
+    //   DVR_WrapperRecordOpenParams_t   param_open;
+    //   DVR_RecordStartParams_t         param_start;
+    //   DVR_RecordStartParams_t         param_update;
+    //   DVR_RecordHandle_t              recorder;
+    //   DVR_RecordEventFunction_t       event_fn;
+    //   void                            *event_userdata;
+
+    //   /*total status = seg_status + status + obsolete*/
+    //   DVR_RecordStatus_t              seg_status;            /**<status of current segment*/
+    //   DVR_WrapperRecordStatus_t       status;                /**<status of remaining segments*/
+    //   uint64_t                        next_segment_id;
+
+    //   DVR_WrapperInfo_t               obsolete;             /**<data obsolete due to the max limit*/
+    // } record;
+    memset(&(ctx->record.seg_status), 0, sizeof(DVR_RecordStatus_t));
+    memset(&(ctx->record.status), 0, sizeof(DVR_WrapperRecordStatus_t));
+    memset(&(ctx->record.obsolete), 0, sizeof(DVR_WrapperInfo_t));
+  }
+
+  start_param = &ctx->record.param_start;
+
+  error = dvr_record_start_segment(ctx->record.recorder, start_param);
+  {
+    DVR_RecordSegmentInfo_t new_seg_info =
+      { .id = start_param->segment.segment_id, };
+    wrapper_addRecordSegment(ctx, &new_seg_info);
+    DVR_WRAPPER_INFO("re record(sn:%ld) started = (%d)start id[%lld]id+[%lld]update id[%lld]\n", ctx->sn, error, start_param->segment.segment_id, ctx->record.next_segment_id, ctx->record.param_update.segment.segment_id);
+    ctx->record.next_segment_id = start_param->segment.segment_id + 1;
+    DVR_RecordStartParams_t *update_param;
+    update_param = &ctx->record.param_update;
+    memcpy(update_param, start_param, sizeof(*update_param));
+    int i = 0;
+    for (i = 0; i < update_param->segment.nb_pids; i++)
+      update_param->segment.pid_action[i] = DVR_RECORD_PID_KEEP;
+  }
+
+  DVR_WRAPPER_INFO("re record(sn:%ld) started = (%d)\n", ctx->sn, error);
+
+  wrapper_mutex_unlock(&ctx->wrapper_lock);
+
+  //start play
+  DVR_WRAPPER_INFO("re start play and clear old status\n");
+  //clear play statue
+  ctx = ctx_getPlayback((unsigned long)playback);
+  if (ctx) {
+    //reset old playback status
+    //     struct {
+    //   DVR_WrapperPlaybackOpenParams_t param_open;
+    //   DVR_PlaybackHandle_t            player;
+    //   DVR_PlaybackEventFunction_t     event_fn;
+    //   void                            *event_userdata;
+
+    //   /*total status = seg_status + status*/
+    //   DVR_PlaybackStatus_t            seg_status;
+    //   DVR_WrapperPlaybackStatus_t     status;
+    //   DVR_PlaybackPids_t              pids_req;
+    //   DVR_PlaybackEvent_t             last_event;
+    //   float                           speed;
+    //   DVR_Bool_t                      reach_end;
+
+    //   DVR_WrapperInfo_t               obsolete;
+    //   DVR_Bool_t                      tf_full;
+    // } playback;
+    ctx->playback.tf_full = DVR_FALSE;
+    ctx->playback.reach_end = DVR_FALSE;
+    memset(&(ctx->playback.last_event), 0, sizeof(DVR_PlaybackEvent_t));
+    memset(&(ctx->playback.seg_status), 0, sizeof(DVR_PlaybackStatus_t));
+    memset(&(ctx->playback.status), 0, sizeof(DVR_WrapperPlaybackStatus_t));
+    memset(&(ctx->playback.obsolete), 0, sizeof(DVR_WrapperInfo_t));
+  }
+  error = dvr_wrapper_start_playback(playback, flags, p_pids);
+  return error;
+}
 
 int dvr_wrapper_stop_playback (DVR_WrapperPlayback_t playback)
 {
@@ -1609,26 +2103,30 @@
   ctx = ctx_getPlayback((unsigned long)playback);
   DVR_RETURN_IF_FALSE(ctx);
 
-  pthread_mutex_lock(&ctx->lock);
-  DVR_WRAPPER_DEBUG(1, "stop playback(sn:%ld) ...\n", ctx->sn);
-  DVR_RETURN_IF_FALSE_WITH_UNLOCK(ctx_valid(ctx), &ctx->lock);
+  wrapper_mutex_lock(&ctx->wrapper_lock);
+  DVR_WRAPPER_INFO("stop playback(sn:%ld) ...\n", ctx->sn);
+  WRAPPER_RETURN_IF_FALSE_WITH_UNLOCK(ctx_valid(ctx), &ctx->wrapper_lock);
 
   error = dvr_playback_stop(ctx->playback.player, DVR_TRUE);
 
   {
     /*remove all segments*/
-    DVR_WrapperPlaybackSegmentInfo_t *pseg;
+    DVR_WrapperPlaybackSegmentInfo_t *p_seg;
 
-    list_for_each_entry(pseg, &ctx->segments, head) {
-      error = dvr_playback_remove_segment(ctx->playback.player, pseg->playback_info.segment_id);
-      DVR_WRAPPER_DEBUG(1, "playback(sn:%ld) remove seg(%lld) (%d)\n",
-        ctx->sn, pseg->playback_info.segment_id, error);
+    // This error is suppressed as the macro code is picked from kernel.
+    // prefetch() here incurring self_assign is used to avoid some compiling
+    // warnings.
+    // coverity[self_assign]
+    list_for_each_entry(p_seg, &ctx->segments, head) {
+      error = dvr_playback_remove_segment(ctx->playback.player, p_seg->playback_info.segment_id);
+      DVR_WRAPPER_INFO("playback(sn:%ld) remove seg(%lld) (%d)\n",
+        ctx->sn, p_seg->playback_info.segment_id, error);
     }
     ctx_freeSegments(ctx);
   }
 
-  DVR_WRAPPER_DEBUG(1, "playback(sn:%ld) stopped (%d)\n", ctx->sn, error);
-  pthread_mutex_unlock(&ctx->lock);
+  DVR_WRAPPER_INFO("playback(sn:%ld) stopped (%d)\n", ctx->sn, error);
+  wrapper_mutex_unlock(&ctx->wrapper_lock);
 
   return error;
 }
@@ -1643,9 +2141,9 @@
   ctx = ctx_getPlayback((unsigned long)playback);
   DVR_RETURN_IF_FALSE(ctx);
 
-  pthread_mutex_lock(&ctx->lock);
-  DVR_WRAPPER_DEBUG(1, "pause playback(sn:%ld) ...\n", ctx->sn);
-  DVR_RETURN_IF_FALSE_WITH_UNLOCK(ctx_valid(ctx), &ctx->lock);
+  wrapper_mutex_lock(&ctx->wrapper_lock);
+  DVR_WRAPPER_INFO("pause playback(sn:%ld) ...\n", ctx->sn);
+  WRAPPER_RETURN_IF_FALSE_WITH_UNLOCK(ctx_valid(ctx), &ctx->wrapper_lock);
   //clear end event
   if (ctx->playback.last_event == DVR_PLAYBACK_EVENT_REACHED_END)
       ctx->playback.last_event = DVR_PLAYBACK_EVENT_TRANSITION_OK;
@@ -1654,8 +2152,8 @@
 
   ctx->playback.speed = 0.0f;
 
-  DVR_WRAPPER_DEBUG(1, "playback(sn:%ld) paused (%d)\n", ctx->sn, error);
-  pthread_mutex_unlock(&ctx->lock);
+  DVR_WRAPPER_INFO("playback(sn:%ld) paused (%d)\n", ctx->sn, error);
+  wrapper_mutex_unlock(&ctx->wrapper_lock);
 
   return error;
 }
@@ -1674,21 +2172,21 @@
   if (dvr_playback_check_limit(ctx->playback.player)) {
     int expired = dvr_playback_calculate_expiredlen(ctx->playback.player);
     if (expired > time_offset) {
-      DVR_WRAPPER_DEBUG(1, "seek before resume reset offset playback(sn:%ld) (off:%d expired:%d)\n",
+      DVR_WRAPPER_INFO("seek before resume reset offset playback(sn:%ld) (off:%d expired:%d)\n",
         ctx->sn, time_offset, expired);
       time_offset = expired;
       dvr_wrapper_seek_playback(playback, time_offset);
     }
   }
-  pthread_mutex_lock(&ctx->lock);
-  DVR_WRAPPER_DEBUG(1, "resume playback(sn:%ld) ...\n", ctx->sn);
-  DVR_RETURN_IF_FALSE_WITH_UNLOCK(ctx_valid(ctx), &ctx->lock);
+  wrapper_mutex_lock(&ctx->wrapper_lock);
+  DVR_WRAPPER_INFO("resume playback(sn:%ld) ...\n", ctx->sn);
+  WRAPPER_RETURN_IF_FALSE_WITH_UNLOCK(ctx_valid(ctx), &ctx->wrapper_lock);
 
   error = dvr_playback_resume(ctx->playback.player);
   ctx->playback.speed = 100.0f;
 
-  DVR_WRAPPER_DEBUG(1, "playback(sn:%ld) resumed (%d)\n", ctx->sn, error);
-  pthread_mutex_unlock(&ctx->lock);
+  DVR_WRAPPER_INFO("playback(sn:%ld) resumed (%d)\n", ctx->sn, error);
+  wrapper_mutex_unlock(&ctx->wrapper_lock);
 
   return error;
 }
@@ -1707,30 +2205,30 @@
   ctx = ctx_getPlayback((unsigned long)playback);
   DVR_RETURN_IF_FALSE(ctx);
 
-  pthread_mutex_lock(&ctx->lock);
-  DVR_WRAPPER_DEBUG(1, "speed playback(sn:%ld) (x%f) .(x%f)..\n", ctx->sn, speed, ctx->playback.speed);
-  DVR_RETURN_IF_FALSE_WITH_UNLOCK(ctx_valid(ctx), &ctx->lock);
+  wrapper_mutex_lock(&ctx->wrapper_lock);
+  DVR_WRAPPER_INFO("speed playback(sn:%ld) (x%f) .(x%f)..\n", ctx->sn, speed, ctx->playback.speed);
+  WRAPPER_RETURN_IF_FALSE_WITH_UNLOCK(ctx_valid(ctx), &ctx->wrapper_lock);
 
   error = dvr_playback_set_speed(ctx->playback.player, dvr_speed);
 
   if (ctx->playback.speed != 0.0f && ctx->playback.speed != 100.0f
       && ctx->playback.last_event == DVR_PLAYBACK_EVENT_REACHED_BEGIN
       && ctx->playback.seg_status.state == DVR_PLAYBACK_STATE_PAUSE) {
-    DVR_WRAPPER_DEBUG(1, "x%f -> x%f, paused, do resume first\n", ctx->playback.speed, speed);
+    DVR_WRAPPER_INFO("x%f -> x%f, paused, do resume first\n", ctx->playback.speed, speed);
     error = dvr_playback_resume(ctx->playback.player);
   } else if (ctx->playback.speed == 0.0f
       && speed != 0.0f
       && speed != 100.0f) {
     /*libdvr do not support pause with speed=0, will not be here*/
-    DVR_WRAPPER_DEBUG(1, "x%f -> x%f, do resume first\n", ctx->playback.speed, speed);
+    DVR_WRAPPER_INFO("x%f -> x%f, do resume first\n", ctx->playback.speed, speed);
     error = dvr_playback_resume(ctx->playback.player);
   }
 
   ctx->playback.speed = speed;
 
-  DVR_WRAPPER_DEBUG(1, "playback(sn:%ld) speeded(x%f) (%d)\n",
+  DVR_WRAPPER_INFO("playback(sn:%ld) speeded(x%f) (%d)\n",
     ctx->sn, speed, error);
-  pthread_mutex_unlock(&ctx->lock);
+  wrapper_mutex_unlock(&ctx->wrapper_lock);
 
   return error;
 }
@@ -1745,15 +2243,15 @@
   ctx = ctx_getPlayback((unsigned long)playback);
   DVR_RETURN_IF_FALSE(ctx);
 
-  pthread_mutex_lock(&ctx->lock);
+  wrapper_mutex_lock(&ctx->wrapper_lock);
 
-  DVR_WRAPPER_DEBUG(1, "setlimit playback(sn:%ld) (time:%lld limit:%d) ...\n", ctx->sn, time, limit);
-  DVR_RETURN_IF_FALSE_WITH_UNLOCK(ctx_valid(ctx), &ctx->lock);
+  DVR_WRAPPER_INFO("set_limit playback(sn:%ld) (time:%lld limit:%d) ...\n", ctx->sn, time, limit);
+  WRAPPER_RETURN_IF_FALSE_WITH_UNLOCK(ctx_valid(ctx), &ctx->wrapper_lock);
 
   error = dvr_playback_setlimit(ctx->playback.player, time, limit);
-  DVR_WRAPPER_DEBUG(1, "playback(sn:%ld) setlimit(time:%lld limit:%d) ...\n", ctx->sn, time, limit);
+  DVR_WRAPPER_INFO("playback(sn:%ld) set_limit(time:%lld limit:%d) ...\n", ctx->sn, time, limit);
 
-  pthread_mutex_unlock(&ctx->lock);
+  wrapper_mutex_unlock(&ctx->wrapper_lock);
 
   return error;
 }
@@ -1762,7 +2260,7 @@
 {
   DVR_WrapperCtx_t *ctx;
   int error;
-  DVR_WrapperPlaybackSegmentInfo_t *pseg;
+  DVR_WrapperPlaybackSegmentInfo_t *p_seg;
   uint64_t segment_id;
   uint32_t off;
   uint64_t last_segment_id;
@@ -1773,10 +2271,10 @@
   ctx = ctx_getPlayback((unsigned long)playback);
   DVR_RETURN_IF_FALSE(ctx);
 
-  pthread_mutex_lock(&ctx->lock);
+  wrapper_mutex_lock(&ctx->wrapper_lock);
 
-  DVR_WRAPPER_DEBUG(1, "seek playback(sn:%ld) (off:%d) ...\n", ctx->sn, time_offset);
-  DVR_RETURN_IF_FALSE_WITH_UNLOCK(ctx_valid(ctx), &ctx->lock);
+  DVR_WRAPPER_INFO("seek playback(sn:%ld) (off:%d) ...\n", ctx->sn, time_offset);
+  WRAPPER_RETURN_IF_FALSE_WITH_UNLOCK(ctx_valid(ctx), &ctx->wrapper_lock);
 
   off = 0;
   segment_id = 0;
@@ -1788,20 +2286,24 @@
   if (dvr_playback_check_limit(ctx->playback.player)) {
     int expired = dvr_playback_calculate_expiredlen(ctx->playback.player);
     if (expired > time_offset) {
-      DVR_WRAPPER_DEBUG(1, "seek reset offset playback(sn:%ld) (off:%d expired:%d)\n",
+      DVR_WRAPPER_INFO("seek reset offset playback(sn:%ld) (off:%d expired:%d)\n",
         ctx->sn, time_offset, expired);
       time_offset = expired;
     }
   }
 
-  list_for_each_entry_reverse(pseg, &ctx->segments, head) {
-    segment_id = pseg->seg_info.id;
+  // This error is suppressed as the macro code is picked from kernel.
+  // prefetch() here incurring self_assign is used to avoid some compiling
+  // warnings.
+  // coverity[self_assign]
+  list_for_each_entry_reverse(p_seg, &ctx->segments, head) {
+    segment_id = p_seg->seg_info.id;
 
-    if ((ctx->playback.obsolete.time + pre_off + pseg->seg_info.duration) > time_offset)
+    if ((ctx->playback.obsolete.time + pre_off + p_seg->seg_info.duration) > time_offset)
         break;
 
-    last_segment_id = pseg->seg_info.id;
-    pre_off += pseg->seg_info.duration;
+    last_segment_id = p_seg->seg_info.id;
+    pre_off += p_seg->seg_info.duration;
   }
 
   if (last_segment_id == segment_id) {
@@ -1813,12 +2315,12 @@
     off = time_offset - pre_off - ctx->playback.obsolete.time;
   }
 
-  DVR_WRAPPER_DEBUG(1, "seek playback(sn:%ld) (seg:%lld, off:%d)\n",
+  DVR_WRAPPER_INFO("seek playback(sn:%ld) (seg:%lld, off:%d)\n",
     ctx->sn, segment_id, off);
   error = dvr_playback_seek(ctx->playback.player, segment_id, off);
-  DVR_WRAPPER_DEBUG(1, "playback(sn:%ld) seeked(off:%d) (%d)\n", ctx->sn, time_offset, error);
+  DVR_WRAPPER_INFO("playback(sn:%ld) seeked(off:%d) (%d)\n", ctx->sn, time_offset, error);
 
-  pthread_mutex_unlock(&ctx->lock);
+  wrapper_mutex_unlock(&ctx->wrapper_lock);
 
   return error;
 }
@@ -1827,7 +2329,7 @@
 {
   DVR_WrapperCtx_t *ctx;
   int error;
-  DVR_WrapperPlaybackSegmentInfo_t *pseg;
+  DVR_WrapperPlaybackSegmentInfo_t *p_seg;
 
   DVR_RETURN_IF_FALSE(playback);
   DVR_RETURN_IF_FALSE(p_pids);
@@ -1835,28 +2337,32 @@
   ctx = ctx_getPlayback((unsigned long)playback);
   DVR_RETURN_IF_FALSE(ctx);
 
-  pthread_mutex_lock(&ctx->lock);
+  wrapper_mutex_lock(&ctx->wrapper_lock);
 
-  DVR_WRAPPER_DEBUG(1, "update playback(sn:%ld) v/a(%d:%d/%d:%d) ...\n",
+  DVR_WRAPPER_INFO("update playback(sn:%ld) v/a(%d:%d/%d:%d) ...\n",
     ctx->sn,
     p_pids->video.pid, p_pids->video.format,
     p_pids->audio.pid, p_pids->audio.format);
-  DVR_RETURN_IF_FALSE_WITH_UNLOCK(ctx_valid(ctx), &ctx->lock);
+  WRAPPER_RETURN_IF_FALSE_WITH_UNLOCK(ctx_valid(ctx), &ctx->wrapper_lock);
 
   ctx->playback.pids_req = *p_pids;
 
   error = 0;
-  list_for_each_entry_reverse(pseg, &ctx->segments, head) {
+  // This error is suppressed as the macro code is picked from kernel.
+  // prefetch() here incurring self_assign is used to avoid some compiling
+  // warnings.
+  // coverity[self_assign]
+  list_for_each_entry_reverse(p_seg, &ctx->segments, head) {
     /*should update the whole list of segments*/
-    /*if (pseg->seg_info.id == ctx->current_segment_id)*/ {
-      /*list_for_each_entry_from(pseg, &ctx->segments, head)*/ {
-        /*check udpate for pids*/
-        if (memcmp(&pseg->playback_info.pids, p_pids, sizeof(*p_pids)) != 0) {
-          pseg->playback_info.pids = *p_pids;
-          error = dvr_playback_update_segment_pids(ctx->playback.player, pseg->seg_info.id, p_pids);
+    /*if (p_seg->seg_info.id == ctx->current_segment_id)*/ {
+      /*list_for_each_entry_from(p_seg, &ctx->segments, head)*/ {
+        /*check update for pids*/
+        if (memcmp(&p_seg->playback_info.pids, p_pids, sizeof(*p_pids)) != 0) {
+          p_seg->playback_info.pids = *p_pids;
+          error = dvr_playback_update_segment_pids(ctx->playback.player, p_seg->seg_info.id, p_pids);
           if (error) {
-            DVR_WRAPPER_DEBUG(1, "failed to playback(sn:%ld) update segment(id:%lld) pids (%d)\n",
-              ctx->sn, pseg->seg_info.id, error);
+            DVR_WRAPPER_INFO("failed to playback(sn:%ld) update segment(id:%lld) pids (%d)\n",
+              ctx->sn, p_seg->seg_info.id, error);
             /*do not break, let list updated*/
           }
         }
@@ -1865,13 +2371,13 @@
     }
   }
 
-  DVR_WRAPPER_DEBUG(1, "update playback(sn:%ld) v/a(%d:%d/%d:%d) (%d)\n",
+  DVR_WRAPPER_INFO("update playback(sn:%ld) v/a(%d:%d/%d:%d) (%d)\n",
     ctx->sn,
     p_pids->video.pid, p_pids->video.format,
     p_pids->audio.pid, p_pids->audio.format,
     error);
 
-  pthread_mutex_unlock(&ctx->lock);
+  wrapper_mutex_unlock(&ctx->wrapper_lock);
 
   return error;
 }
@@ -1880,7 +2386,7 @@
 {
   DVR_WrapperCtx_t *ctx;
   int error;
-  DVR_WrapperPlaybackSegmentInfo_t *pseg;
+  DVR_WrapperPlaybackSegmentInfo_t *p_seg;
 
   DVR_RETURN_IF_FALSE(playback);
   DVR_RETURN_IF_FALSE(p_pids);
@@ -1888,28 +2394,32 @@
   ctx = ctx_getPlayback((unsigned long)playback);
   DVR_RETURN_IF_FALSE(ctx);
 
-  pthread_mutex_lock(&ctx->lock);
+  wrapper_mutex_lock(&ctx->wrapper_lock);
 
-  DVR_WRAPPER_DEBUG(1, "update playback(sn:%ld) v/a(%d:%d/%d:%d) ...\n",
+  DVR_WRAPPER_INFO("update playback(sn:%ld) v/a(%d:%d/%d:%d) ...\n",
     ctx->sn,
     p_pids->video.pid, p_pids->video.format,
     p_pids->audio.pid, p_pids->audio.format);
-  DVR_RETURN_IF_FALSE_WITH_UNLOCK(ctx_valid(ctx), &ctx->lock);
+  WRAPPER_RETURN_IF_FALSE_WITH_UNLOCK(ctx_valid(ctx), &ctx->wrapper_lock);
 
   ctx->playback.pids_req = *p_pids;
 
   error = 0;
-  list_for_each_entry_reverse(pseg, &ctx->segments, head) {
+  // This error is suppressed as the macro code is picked from kernel.
+  // prefetch() here incurring self_assign is used to avoid some compiling
+  // warnings.
+  // coverity[self_assign]
+  list_for_each_entry_reverse(p_seg, &ctx->segments, head) {
     /*should update the whole list of segments*/
-    /*if (pseg->seg_info.id == ctx->current_segment_id)*/ {
-      /*list_for_each_entry_from(pseg, &ctx->segments, head)*/ {
-        /*check udpate for pids*/
-        if (memcmp(&pseg->playback_info.pids, p_pids, sizeof(*p_pids)) != 0) {
-          pseg->playback_info.pids = *p_pids;
-          error = dvr_playback_only_update_segment_pids(ctx->playback.player, pseg->seg_info.id, p_pids);
+    /*if (p_seg->seg_info.id == ctx->current_segment_id)*/ {
+      /*list_for_each_entry_from(p_seg, &ctx->segments, head)*/ {
+        /*check update for pids*/
+        if (memcmp(&p_seg->playback_info.pids, p_pids, sizeof(*p_pids)) != 0) {
+          p_seg->playback_info.pids = *p_pids;
+          error = dvr_playback_only_update_segment_pids(ctx->playback.player, p_seg->seg_info.id, p_pids);
           if (error) {
-            DVR_WRAPPER_DEBUG(1, "failed to playback(sn:%ld) update segment(id:%lld) pids (%d)\n",
-              ctx->sn, pseg->seg_info.id, error);
+            DVR_WRAPPER_INFO("failed to playback(sn:%ld) update segment(id:%lld) pids (%d)\n",
+              ctx->sn, p_seg->seg_info.id, error);
             /*do not break, let list updated*/
           }
         }
@@ -1918,13 +2428,13 @@
     }
   }
 
-  DVR_WRAPPER_DEBUG(1, "update playback(sn:%ld) v/a(%d:%d/%d:%d) (%d)\n",
+  DVR_WRAPPER_INFO("update playback(sn:%ld) v/a(%d:%d/%d:%d) (%d)\n",
     ctx->sn,
     p_pids->video.pid, p_pids->video.format,
     p_pids->audio.pid, p_pids->audio.format,
     error);
 
-  pthread_mutex_unlock(&ctx->lock);
+  wrapper_mutex_unlock(&ctx->wrapper_lock);
 
   return error;
 }
@@ -1942,23 +2452,23 @@
   ctx = ctx_getPlayback((unsigned long)playback);
   DVR_RETURN_IF_FALSE(ctx);
 
-  pthread_mutex_lock(&ctx->lock);
+  wrapper_mutex_lock(&ctx->wrapper_lock);
 
-  DVR_WRAPPER_DEBUG(1, "get playback(sn:%ld) status ...\n", ctx->sn);
-  DVR_RETURN_IF_FALSE_WITH_UNLOCK(ctx_valid(ctx), &ctx->lock);
+  DVR_WRAPPER_INFO("get playback(sn:%ld) status ...\n", ctx->sn);
+  WRAPPER_RETURN_IF_FALSE_WITH_UNLOCK(ctx_valid(ctx), &ctx->wrapper_lock);
 
   error = dvr_playback_get_status(ctx->playback.player, &play_status);
-  DVR_WRAPPER_DEBUG(1, "playback(sn:%ld) get status (%d)\n", ctx->sn, error);
+  DVR_WRAPPER_INFO("playback(sn:%ld) get status (%d)\n", ctx->sn, error);
 
   ctx->playback.seg_status = play_status;
   error = process_generatePlaybackStatus(ctx, &s);
 
   if (ctx->playback.reach_end == DVR_TRUE && ctx->playback.param_open.is_timeshift == DVR_FALSE) {
     //reach end need set full time to cur.so app can exist playback.
-    DVR_WRAPPER_DEBUG(1, "set cur time to full time, reach end occur");
+    DVR_WRAPPER_INFO("set cur time to full time, reach end occur");
     s.info_cur.time = s.info_full.time;
   }
-  DVR_WRAPPER_DEBUG(1, "playback(sn:%ld) state/cur/full/obsl(%d/%ld/%ld/%ld) (%d)\n",
+  DVR_WRAPPER_INFO("playback(sn:%ld) state/cur/full/obsolete(%d/%ld/%ld/%ld) (%d)\n",
     ctx->sn,
     s.state,
     s.info_cur.time,
@@ -1968,7 +2478,7 @@
 
   *status = s;
 
-  pthread_mutex_unlock(&ctx->lock);
+  wrapper_mutex_unlock(&ctx->wrapper_lock);
 
   return error;
 }
@@ -1984,9 +2494,9 @@
   ctx = ctx_getPlayback((unsigned long)playback);
   DVR_RETURN_IF_FALSE(ctx);
 
-  pthread_mutex_lock(&ctx->lock);
+  wrapper_mutex_lock(&ctx->wrapper_lock);
   error = dvr_playback_set_secure_buffer(ctx->playback.player, p_secure_buf, len);
-  pthread_mutex_unlock(&ctx->lock);
+  wrapper_mutex_unlock(&ctx->wrapper_lock);
   return error;
 }
 
@@ -2001,9 +2511,9 @@
   ctx = ctx_getPlayback((unsigned long)playback);
   DVR_RETURN_IF_FALSE(ctx);
 
-  pthread_mutex_lock(&ctx->lock);
+  wrapper_mutex_lock(&ctx->wrapper_lock);
   error = dvr_playback_set_decrypt_callback(ctx->playback.player, func, userdata);
-  pthread_mutex_unlock(&ctx->lock);
+  wrapper_mutex_unlock(&ctx->wrapper_lock);
   return error;
 }
 
@@ -2044,61 +2554,143 @@
         &p_info->time,
         &p_info->pkts) == 3)) {
       fclose(fp);
-      DVR_WRAPPER_DEBUG(1, "rec(%s) t/s/p:(%lu/%llu/%u)\n", location, p_info->time, p_info->size, p_info->pkts);
+      DVR_WRAPPER_INFO("rec(%s) t/s/p:(%lu/%llu/%u)\n", location, p_info->time, p_info->size, p_info->pkts);
       return DVR_SUCCESS;
     }
     fclose(fp);
   }
 
   /*fallback, slow on mass files*/
-  DVR_WRAPPER_DEBUG(1, "rec '%s.stats' invalid.\n", location);
+  DVR_WRAPPER_INFO("rec '%s.stats' invalid.\n", location);
 
   int error;
   uint32_t n_ids;
   uint64_t *p_ids;
-  DVR_RecordSegmentInfo_t info;
 
-  memset(&info, 0, sizeof(info));
-  error = dvr_segment_get_list(fpath, &n_ids, &p_ids);
+  error = dvr_segment_get_list(location, &n_ids, &p_ids);
+
   if (!error) {
      int i;
-     for (i = 0; i < n_ids; i++) {
-        error = dvr_segment_get_info(fpath, p_ids[i], &info);
-        if (!error) {
-           p_info->size += info.size;
-           p_info->time += info.duration;
-           p_info->pkts += info.nb_packets;
-        } else {
-           DVR_WRAPPER_DEBUG(1, "%s:%lld get seg info fail.\n", fpath, p_ids[i]);
-           break;
-        }
-     }
-     free(p_ids);
+     struct list_head           info_list;         /**< segment list head*/
+    INIT_LIST_HEAD(&info_list);
+
+    //we need free info list buf when we used end.
+    error = dvr_segment_get_allInfo(location, &info_list);
+    if (error == DVR_FAILURE) {
+      DVR_RecordSegmentInfo_t info = { .id = 0, .nb_pids = 0,
+        .pids = {0}, .duration = 0, .size = 0, .nb_packets = 0 };
+
+      memset(&info, 0, sizeof(info));
+      error = DVR_FAILURE;
+      DVR_WRAPPER_INFO("fail to get seg info (location:%s, seg:%llu), (error:%d)\n",
+        location, 0, error);
+
+      // Tainted data issue originating from fgets seem false positive, so we
+      // just suppress it here.
+      // coverity[tainted_data]
+      for (i = 0; i < n_ids; i++) {
+          error = dvr_segment_get_info(location, p_ids[i], &info);
+          if (!error) {
+            p_info->size += info.size;
+            p_info->time += info.duration;
+            p_info->pkts += info.nb_packets;
+          } else {
+            DVR_WRAPPER_INFO("%s:%lld get seg info fail.\n", location, p_ids[i]);
+            break;
+          }
+      }
+    } else {
+      DVR_WRAPPER_INFO("get list segment_nb::%d",n_ids);
+      // Tainted data issue originating from fgets seem false positive, so we
+      // just suppress it here.
+      // coverity[tainted_data]
+      for (i = 0; i < n_ids; i++) {
+
+          DVR_RecordSegmentInfo_t *seg_info;
+          DVR_PlaybackSegmentFlag_t flags;
+          int found = 0;
+          // This error is suppressed as the macro code is picked from kernel.
+          // prefetch() here incurring self_assign is used to avoid some compiling
+          // warnings.
+          // coverity[self_assign]
+          list_for_each_entry(seg_info, &info_list, head)
+          {
+            if (seg_info->id == p_ids[i]) {
+              found = 1;
+              break;
+            }
+          }
+          if (!found) {
+              DVR_WRAPPER_INFO("get segment info::%d [%d]n_ids[%d]error", i, p_ids[i], n_ids);
+              if (p_ids[i] == n_ids - 1) {
+                DVR_RecordSegmentInfo_t info = { .id = 0, .nb_pids = 0,
+                  .pids = {0}, .duration = 0, .size = 0, .nb_packets = 0 };
+                DVR_WRAPPER_INFO("get last segment info::%d [%d]n_ids[%d] from subfile", i, p_ids[i], n_ids);
+                error = dvr_segment_get_info(location, p_ids[i], &info);
+                if (!error) {
+                  p_info->size += info.size;
+                  p_info->time += info.duration;
+                  p_info->pkts += info.nb_packets;
+                } else {
+                  DVR_WRAPPER_INFO("%s:%lld get seg info fail.\n", location, p_ids[i]);
+                  break;
+                }
+              }
+              continue;
+          }
+
+          if (!error) {
+            p_info->size += seg_info->size;
+            p_info->time += seg_info->duration;
+            p_info->pkts += seg_info->nb_packets;
+          } else {
+            DVR_WRAPPER_INFO("%s:%lld get seg info fail.\n", location, p_ids[i]);
+            break;
+          }
+      }
+      //free list
+      DVR_RecordSegmentInfo_t *segment = NULL;
+      DVR_RecordSegmentInfo_t *segment_tmp = NULL;
+      list_for_each_entry_safe(segment, segment_tmp, &info_list, head)
+      {
+          if (segment) {
+            list_del(&segment->head);
+            free(segment);
+          }
+      }
+    }
+    free(p_ids);
   } else {
      n_ids = 0;
   }
-  DVR_WRAPPER_DEBUG(1, "rec(%s)... t/s/p:(%lu/%llu/%u) segs(%u) error(%d)\n", location, p_info->time, p_info->size, p_info->pkts, n_ids, error);
+  DVR_WRAPPER_INFO("rec(%s)... t/s/p:(%lu/%llu/%u) segs(%u) error(%d)\n", location, p_info->time, p_info->size, p_info->pkts, n_ids, error);
 
   return (error)? DVR_FAILURE : DVR_SUCCESS;
 }
 
 static DVR_Result_t wrapper_record_event_handler(DVR_RecordEvent_t event, void *params, void *userdata)
 {
-  DVR_WrapperEventCtx_t evt;
+  DVR_WrapperEventCtx_t evt = {
+    .sn = (unsigned long)userdata,
+    .type = W_REC,
+    .record.event = event,
+    .record.status = *(DVR_RecordStatus_t *)params
+  };
 
   DVR_RETURN_IF_FALSE(userdata);
 
-  evt.sn = (unsigned long)userdata;
-  evt.type = W_REC;
-  evt.record.event = event;
-  evt.record.status = *(DVR_RecordStatus_t *)params;
-  DVR_WRAPPER_DEBUG(1, "evt[sn:%ld, record, evt:0x%x]\n", evt.sn, evt.record.event);
+  DVR_WRAPPER_INFO("evt[sn:%ld, record, evt:0x%x]\n", evt.sn, evt.record.event);
   return ctx_addRecordEvent(&evt);
 }
 
 static DVR_Result_t wrapper_playback_event_handler(DVR_PlaybackEvent_t event, void *params, void *userdata)
 {
-  DVR_WrapperEventCtx_t evt;
+  DVR_WrapperEventCtx_t evt = {
+    .sn = (unsigned long)userdata,
+    .type = W_PLAYBACK,
+    .playback.event = event,
+    .playback.status = *(DVR_Play_Notify_t *)params
+  };
 
   DVR_RETURN_IF_FALSE(userdata);
 
@@ -2106,13 +2698,13 @@
   evt.type = W_PLAYBACK;
   evt.playback.event = event;
   evt.playback.status = *(DVR_Play_Notify_t *)params;
-  DVR_WRAPPER_DEBUG(1, "evt[sn:%ld, playbck, evt:0x%x]\n", evt.sn, evt.playback.event);
+  DVR_WRAPPER_INFO("evt[sn:%ld, playback, evt:0x%x]\n", evt.sn, evt.playback.event);
   return ctx_addPlaybackEvent(&evt);
 }
 
 static inline int process_notifyRecord(DVR_WrapperCtx_t *ctx, DVR_RecordEvent_t evt, DVR_WrapperRecordStatus_t *status)
 {
-  DVR_WRAPPER_DEBUG(1, "notify(sn:%ld) evt(0x%x) statistic:time/size/pkts(%ld/%lld/%u) obsl:(%ld/%llu/%u)\n",
+  DVR_WRAPPER_INFO("notify(sn:%ld) evt(0x%x) statistic:time/size/pkts(%ld/%lld/%u) obsolete:(%ld/%llu/%u)\n",
     ctx->sn,
     evt,
     status->info.time,
@@ -2145,6 +2737,8 @@
         p_status->info.time - p_status->info_obsolete.time,
         p_status->info.pkts - p_status->info_obsolete.pkts);
     fputs(buf, fp);
+    fflush(fp);
+    fsync(fileno(fp));
     fclose(fp);
     return DVR_SUCCESS;
   }
@@ -2178,20 +2772,20 @@
     wrapper_addRecordSegment(ctx, &new_seg_info);
   }
 
-  DVR_WRAPPER_DEBUG(1, "record next segment(%llu)=(%d)\n", ctx->record.param_update.segment.segment_id, error);
+  DVR_WRAPPER_INFO("record next segment(%llu)=(%d)\n", ctx->record.param_update.segment.segment_id, error);
   return error;
 }
 
-static inline int record_removeSegment(DVR_WrapperCtx_t *ctx, DVR_WrapperRecordSegmentInfo_t *pseg)
+static inline int record_removeSegment(DVR_WrapperCtx_t *ctx, DVR_WrapperRecordSegmentInfo_t *p_seg)
 {
-  return wrapper_removeRecordSegment(ctx, pseg);
+  return wrapper_removeRecordSegment(ctx, p_seg);
 }
 
 /*should run periodically to update the current status*/
 static int process_generateRecordStatus(DVR_WrapperCtx_t *ctx, DVR_WrapperRecordStatus_t *status)
 {
   /*the current seg is not covered in the statistics*/
-  DVR_WrapperRecordSegmentInfo_t *pseg;
+  DVR_WrapperRecordSegmentInfo_t *p_seg;
 
   /*re-calculate the all segments*/
   memset(&ctx->record.status, 0, sizeof(ctx->record.status));
@@ -2203,11 +2797,15 @@
     sizeof(ctx->record.status.pids.pids));
   ctx->current_segment_id = ctx->record.seg_status.info.id;
 
-  list_for_each_entry_reverse(pseg, &ctx->segments, head) {
-    if (pseg->info.id != ctx->record.seg_status.info.id) {
-      ctx->record.status.info.time += pseg->info.duration;
-      ctx->record.status.info.size += pseg->info.size;
-      ctx->record.status.info.pkts += pseg->info.nb_packets;
+  // This error is suppressed as the macro code is picked from kernel.
+  // prefetch() here incurring self_assign is used to avoid some compiling
+  // warnings.
+  // coverity[self_assign]
+  list_for_each_entry_reverse(p_seg, &ctx->segments, head) {
+    if (p_seg->info.id != ctx->record.seg_status.info.id) {
+      ctx->record.status.info.time += p_seg->info.duration;
+      ctx->record.status.info.size += p_seg->info.size;
+      ctx->record.status.info.pkts += p_seg->info.nb_packets;
     }
   }
 
@@ -2232,10 +2830,10 @@
 
   memset(&status, 0, sizeof(status));
 
-  DVR_WRAPPER_DEBUG(1, "evt (sn:%ld) 0x%x (state:%d)\n",
+  DVR_WRAPPER_INFO("evt (sn:%ld) 0x%x (state:%d)\n",
     evt->sn, evt->record.event, evt->record.status.state);
   if (ctx->record.param_update.segment.segment_id != evt->record.status.info.id) {
-    DVR_WRAPPER_DEBUG(1, "evt (sn:%ld) cur id:0x%x (event id:%d)\n",
+    DVR_WRAPPER_INFO("evt (sn:%ld) cur id:0x%x (event id:%d)\n",
     evt->sn, (int)ctx->record.param_update.segment.segment_id, (int)evt->record.status.info.id);
     return 0;
   }
@@ -2265,14 +2863,14 @@
           /*restart to next segment*/
           if (ctx->record.param_open.segment_size
               && evt->record.status.info.size >= ctx->record.param_open.segment_size) {
-            DVR_WRAPPER_DEBUG(1, "start new segment for record(%lu), reaches segment size limit, cur(%zu) max(%lld)\n",
+            DVR_WRAPPER_INFO("start new segment for record(%lu), reaches segment size limit, cur(%zu) max(%lld)\n",
               ctx->sn,
               evt->record.status.info.size,
               ctx->record.param_open.segment_size);
             if (record_startNextSegment(ctx) != DVR_SUCCESS) {
               /*should notify the recording's stop*/
               int error = dvr_record_close(ctx->record.recorder);
-              DVR_WRAPPER_DEBUG(1, "stop record(%lu)=%d, failed to start new segment for recording.",
+              DVR_WRAPPER_INFO("stop record(%lu)=%d, failed to start new segment for recording.",
                 ctx->sn, error);
               status.state = DVR_RECORD_STATE_CLOSED;
               process_notifyRecord(ctx, DVR_RECORD_EVENT_WRITE_ERROR, &status);
@@ -2283,21 +2881,21 @@
           if (ctx->record.param_open.is_timeshift
               && ctx->record.param_open.max_time
               && status.info.time >= ctx->record.param_open.max_time) {
-            DVR_WrapperRecordSegmentInfo_t *pseg;
+            DVR_WrapperRecordSegmentInfo_t *p_seg;
 
             /*as the player do not support null playlist,
               there must be one segment existed at any time,
               we have to keep two segments before remove one*/
-            pseg = list_last_entry(&ctx->segments, DVR_WrapperRecordSegmentInfo_t, head);
-            if (pseg == list_first_entry(&ctx->segments, DVR_WrapperRecordSegmentInfo_t, head)) {
+            p_seg = list_last_entry(&ctx->segments, DVR_WrapperRecordSegmentInfo_t, head);
+            if (p_seg == list_first_entry(&ctx->segments, DVR_WrapperRecordSegmentInfo_t, head)) {
               /*only one segment, waiting for more*/
-              DVR_WRAPPER_DEBUG(1, "warning: the size(%lld) of max_time(%ld) of record < max size of segment(%lld)\n",
+              DVR_WRAPPER_INFO("warning: the size(%lld) of max_time(%ld) of record < max size of segment(%lld)\n",
                 status.info.size,
                 ctx->record.param_open.max_time,
                 ctx->record.param_open.segment_size);
             } else {
               /*timeshifting, remove the 1st segment and notify the player*/
-              record_removeSegment(ctx, pseg);
+              record_removeSegment(ctx, p_seg);
 
               process_generateRecordStatus(ctx, &status);
               process_notifyRecord(ctx, evt->record.event, &status);
@@ -2305,26 +2903,33 @@
             }
           }
 
-          if (ctx->record.param_open.is_timeshift
-              && ctx->record.param_open.max_size
-              && status.info.size >= ctx->record.param_open.max_size) {
-            DVR_WrapperRecordSegmentInfo_t *pseg;
+          const loff_t actual_size = status.info.size;
+          const loff_t max_size = ctx->record.param_open.max_size;
+          const loff_t segment_size = ctx->record.param_open.segment_size;
 
-            /*as the player do not support null playlist,
-              there must be one segment existed at any time,
-              we have to keep two segments before remove one*/
-            pseg = list_last_entry(&ctx->segments, DVR_WrapperRecordSegmentInfo_t, head);
-            if (pseg == list_first_entry(&ctx->segments, DVR_WrapperRecordSegmentInfo_t, head)) {
-              /*only one segment, waiting for more*/
-              DVR_WRAPPER_DEBUG(1, "warning: the size(%lld) of record < max size of segment(%lld)\n",
-                status.info.size,
-                ctx->record.param_open.segment_size);
+          if (ctx->record.param_open.is_timeshift && max_size) {
+            if (actual_size >= max_size) {
+              DVR_WrapperRecordSegmentInfo_t *p_seg;
+              /*as the player do not support null playlist,
+                there must be one segment existed at any time,
+                we have to keep two segments before remove one*/
+              p_seg = list_last_entry(&ctx->segments, DVR_WrapperRecordSegmentInfo_t, head);
+              if (p_seg == list_first_entry(&ctx->segments, DVR_WrapperRecordSegmentInfo_t, head)) {
+                /*only one segment, waiting for more*/
+                DVR_WRAPPER_INFO("warning: the size(%lld) of record < max size of segment(%lld)\n",
+                  actual_size, segment_size);
+              } else {
+                record_removeSegment(ctx, p_seg);
+
+                process_generateRecordStatus(ctx, &status);
+                process_notifyRecord(ctx, evt->record.event, &status);
+                wrapper_saveRecordStatistics(ctx->record.param_open.location, &status);
+              }
+              if (actual_size >= max_size + segment_size/2) {
+                dvr_record_discard_coming_data(ctx->record.recorder,DVR_TRUE);
+              }
             } else {
-              record_removeSegment(ctx, pseg);
-
-              process_generateRecordStatus(ctx, &status);
-              process_notifyRecord(ctx, evt->record.event, &status);
-              wrapper_saveRecordStatistics(ctx->record.param_open.location, &status);
+              dvr_record_discard_coming_data(ctx->record.recorder,DVR_FALSE);
             }
           }
         } break;
@@ -2353,24 +2958,30 @@
 
 static inline int process_notifyPlayback(DVR_WrapperCtx_t *ctx, DVR_PlaybackEvent_t evt, DVR_WrapperPlaybackStatus_t *status)
 {
-  DVR_WRAPPER_DEBUG(1, "notify(sn:%ld) evt(0x%x) statistics:state/cur/full/obsl(%d/%ld/%ld/%ld)\n",
-    ctx->sn,
-    evt,
-    status->state,
-    status->info_cur.time,
-    status->info_full.time,
-    status->info_obsolete.time);
+  DVR_RETURN_IF_FALSE(ctx->playback.event_fn != NULL);
 
-  if (ctx->playback.event_fn)
-    return ctx->playback.event_fn(evt, status, ctx->playback.event_userdata);
-  return 0;
+  const time_t cur_time = status->info_cur.time;
+  const time_t full_time = status->info_full.time;
+  const time_t obsolete_time = status->info_obsolete.time;
+  const time_t origin_offset = cur_time + obsolete_time;
+  DVR_WRAPPER_INFO("playback progress notify(sn:%ld) evt(0x%x)"
+      " actual_slider_pos: %02d:%02d:%02d.%03d/%02d:%02d:%02d.%03d (%7ld ms/%7ld ms),"
+      " offset_from_origin: %02d:%02d:%02d.%03d (%7ld ms),"
+      " dump status:state/cur/full/obsolete(%d/%ld/%ld/%ld)",
+      ctx->sn,evt,cur_time/1000/3600,cur_time/1000%3600/60,cur_time/1000%60,cur_time%1000,
+      full_time/1000/3600,full_time/1000%3600/60,full_time/1000%60,full_time%1000,
+      cur_time,full_time,
+      origin_offset/1000/3600,origin_offset/1000%3600/60,origin_offset/1000%60,origin_offset%1000,
+      origin_offset,status->state,cur_time,full_time,obsolete_time);
+
+  return ctx->playback.event_fn(evt, status, ctx->playback.event_userdata);
 }
 
 /*should run periodically to update the current status*/
 static int process_generatePlaybackStatus(DVR_WrapperCtx_t *ctx, DVR_WrapperPlaybackStatus_t *status)
 {
   /*the current seg is not covered in the statistics*/
-  DVR_WrapperPlaybackSegmentInfo_t *pseg;
+  DVR_WrapperPlaybackSegmentInfo_t *p_seg;
 
   memset(&ctx->playback.status, 0, sizeof(ctx->playback.status));
   ctx->playback.status.pids = ctx->playback.pids_req;
@@ -2380,24 +2991,50 @@
   ctx->playback.status.flags = ctx->playback.seg_status.flags;
   ctx->current_segment_id = ctx->playback.seg_status.segment_id;
 
-  list_for_each_entry_reverse(pseg, &ctx->segments, head) {
-    if (pseg->seg_info.id == ctx->playback.seg_status.segment_id)
+  // This error is suppressed as the macro code is picked from kernel.
+  // prefetch() here incurring self_assign is used to avoid some compiling
+  // warnings.
+  // coverity[self_assign]
+  list_for_each_entry_reverse(p_seg, &ctx->segments, head) {
+    if (p_seg->seg_info.id == ctx->playback.seg_status.segment_id) {
+        DVR_WRAPPER_INFO("calculate cur time :[%lld]time[%d]\n", p_seg->seg_info.id, p_seg->seg_info.duration);
         break;
-    ctx->playback.status.info_cur.time += pseg->seg_info.duration;
-    ctx->playback.status.info_cur.size += pseg->seg_info.size;
-    ctx->playback.status.info_cur.pkts += pseg->seg_info.nb_packets;
+    }
+
+    ctx->playback.status.info_cur.time += p_seg->seg_info.duration;
+    ctx->playback.status.info_cur.size += p_seg->seg_info.size;
+    ctx->playback.status.info_cur.pkts += p_seg->seg_info.nb_packets;
   }
-  list_for_each_entry_reverse(pseg, &ctx->segments, head) {
-    ctx->playback.status.info_full.time += pseg->seg_info.duration;
-    ctx->playback.status.info_full.size += pseg->seg_info.size;
-    ctx->playback.status.info_full.pkts += pseg->seg_info.nb_packets;
+  // This error is suppressed as the macro code is picked from kernel.
+  // prefetch() here incurring self_assign is used to avoid some compiling
+  // warnings.
+  // coverity[self_assign]
+  list_for_each_entry_reverse(p_seg, &ctx->segments, head) {
+    ctx->playback.status.info_full.time += p_seg->seg_info.duration;
+    ctx->playback.status.info_full.size += p_seg->seg_info.size;
+    ctx->playback.status.info_full.pkts += p_seg->seg_info.nb_packets;
+    DVR_WRAPPER_INFO("calculate full time :[%lld]time[%d]\n", p_seg->seg_info.id, p_seg->seg_info.duration);
   }
 
   if (status) {
     *status = ctx->playback.status;
     /*deal with current, lack size and pkts with the current*/
     status->info_cur.time += ctx->playback.seg_status.time_cur;
-    status->info_obsolete.time = ctx->playback.obsolete.time;
+    //get last segment id
+    DVR_WrapperRecordSegmentInfo_t *p_seg;
+
+    p_seg = list_last_entry(&ctx->segments, DVR_WrapperRecordSegmentInfo_t, head);
+    if (ctx->playback.tf_full == DVR_TRUE && p_seg->info.id == ctx->current_segment_id) {
+      status->disguised_info_obsolete.time = ctx->playback.obsolete.time + ctx->playback.seg_status.time_cur;
+      status->info_obsolete.time = ctx->playback.obsolete.time;
+      DVR_WRAPPER_INFO("warning change start time :id[%lld] [%d]cur[%d]\n", p_seg->info.id, status->info_obsolete.time, status->info_cur.time);
+    }
+    else
+    {
+        DVR_WRAPPER_INFO("warning not change start time :ctx->playback.tf_full[%d]id[%lld] [%lld] cur[%d]\n",ctx->playback.tf_full , p_seg->info.id, ctx->current_segment_id, status->info_cur.time);
+        status->info_obsolete.time = ctx->playback.obsolete.time;
+        status->disguised_info_obsolete.time = ctx->playback.obsolete.time;
+    }
   }
 
   return DVR_SUCCESS;
@@ -2405,7 +3042,7 @@
 
 static int process_handlePlaybackEvent(DVR_WrapperEventCtx_t *evt, DVR_WrapperCtx_t *ctx)
 {
-  DVR_WRAPPER_DEBUG(1, "evt (sn:%ld) 0x%x (state:%d) cur(%lld:%u/%u)\n",
+  DVR_WRAPPER_INFO("evt (sn:%ld) 0x%x (state:%d) cur(%lld:%u/%u)\n",
     evt->sn, evt->playback.event,
     evt->playback.status.play_status.state,
     evt->playback.status.play_status.segment_id,
@@ -2439,7 +3076,7 @@
       process_generatePlaybackStatus(ctx, &status);
 
       if (evt->playback.event == DVR_PLAYBACK_EVENT_REACHED_END) {
-        DVR_WRAPPER_DEBUG(1, "playback(sn:%ld) event:0x%x\n", evt->sn, evt->playback.event);
+        DVR_WRAPPER_INFO("playback(sn:%ld) event:0x%x\n", evt->sn, evt->playback.event);
         if (ctx->playback.param_open.is_timeshift
           || ctx_isPlay_recording(ctx->playback.param_open.location)) {
           /*wait for more data in recording*/
@@ -2462,11 +3099,11 @@
     case DVR_PLAYBACK_EVENT_KEY_FAILURE:
     case DVR_PLAYBACK_EVENT_NO_KEY:
     {
-      DVR_WRAPPER_DEBUG(1, "playback(sn:%ld) error event:0x%x\n", evt->sn, evt->playback.event);
+      DVR_WRAPPER_INFO("playback(sn:%ld) error event:0x%x\n", evt->sn, evt->playback.event);
     } break;
     default:
     {
-      DVR_WRAPPER_DEBUG(1, "playback(sn:%ld) unknown event:0x%x\n", evt->sn, evt->playback.event);
+      DVR_WRAPPER_INFO("playback(sn:%ld) unknown event:0x%x\n", evt->sn, evt->playback.event);
     } break;
   }
   return 0;
@@ -2477,3 +3114,46 @@
   return (evt->type == W_REC)? process_handleRecordEvent(evt, ctx) : process_handlePlaybackEvent(evt, ctx);
 }
 
+int dvr_wrapper_set_log_level (int level)
+{
+  if (level<LOG_LV_DEFAULT || level>LOG_LV_FATAL) {
+    DVR_WRAPPER_ERROR("Invalid dvr log level:%d", g_dvr_log_level);
+    return DVR_FAILURE;
+  }
+  g_dvr_log_level = level;
+  DVR_WRAPPER_INFO("New dvr log level:%d", g_dvr_log_level);
+  return DVR_SUCCESS;
+}
+
+int dvr_wrapper_set_ac4_preselection_id(DVR_WrapperPlayback_t playback, int presel_id)
+{
+  DVR_WrapperCtx_t *ctx;
+  int error;
+
+  DVR_RETURN_IF_FALSE(playback==NULL);
+
+  ctx = ctx_getPlayback((unsigned long)playback);
+  DVR_RETURN_IF_FALSE(ctx);
+
+  wrapper_mutex_lock(&ctx->wrapper_lock);
+
+  WRAPPER_RETURN_IF_FALSE_WITH_UNLOCK(ctx_valid(ctx), &ctx->wrapper_lock);
+
+  DVR_WRAPPER_INFO("set ac4 preselection id: %d", presel_id);
+  error = dvr_playback_set_ac4_preselection_id(ctx->playback.player, presel_id);
+
+  wrapper_mutex_unlock(&ctx->wrapper_lock);
+
+  return error;
+}
+
+int dvr_wrapper_property_set(const char* prop_name, const char* prop_value)
+{
+  return dvr_prop_write(prop_name,prop_value);
+}
+
+int dvr_wrapper_property_get(const char* prop_name, char* prop_value, int length)
+{
+  return dvr_prop_read(prop_name,prop_value,length);
+}
+
diff --git a/src/record_device.c b/src/record_device.c
index 3e1c29f..34e8380 100644
--- a/src/record_device.c
+++ b/src/record_device.c
@@ -66,7 +66,7 @@
   }
 };
 /*define sec dmx function api ptr*/
-static int SECDMX_API_INIT = 0;
+static void* secdmx_handle = NULL;
 int (*SECDMX_Init_Ptr)(void);
 int (*SECDMX_Deinit_Ptr)(void);
 int (*SECDMX_AllocateDVRBuffer_Ptr)(int sid, size_t size, size_t *addr);
@@ -77,24 +77,24 @@
 int (*SECDMX_GetOutputBufferStatus_Ptr)(size_t handle, size_t *start_addr, size_t *len);
 int (*SECDMX_ProcessData_Ptr)(int sid, size_t wp);
 
-int load_secdmx_api(void)
+static void* load_secdmx_api(void)
 {
-  if (SECDMX_API_INIT == 1) {
-    return 0;
+  if (secdmx_handle != NULL) {
+    return secdmx_handle;
   }
-  SECDMX_API_INIT = 1;
   void* handle = NULL;
   handle = dlopen("libdmx_client_sys.so", RTLD_NOW);//RTLD_NOW  RTLD_LAZY
 
   if (handle == NULL) {
-    DVR_DEBUG(0, "load_secdmx_api load libdmx_client_sys error[%s] no:%d", strerror(errno), errno);
+    DVR_ERROR("load_secdmx_api load libdmx_client_sys error[%s] no:%d", strerror(errno), errno);
     handle = dlopen("libdmx_client.so", RTLD_NOW);//RTLD_NOW  RTLD_LAZY
   }
 
   if (handle == NULL) {
-    DVR_DEBUG(0, "load_secdmx_api load libdmx_client error[%s] no:%d", strerror(errno), errno);
-    return 0;
+    DVR_ERROR("load_secdmx_api load libdmx_client error[%s] no:%d", strerror(errno), errno);
+    return NULL;
   }
+  secdmx_handle = handle;
 
   SECDMX_Init_Ptr = dlsym(handle, "SECDMX_Init");
   SECDMX_Deinit_Ptr = dlsym(handle, "SECDMX_Deinit");
@@ -106,7 +106,18 @@
   SECDMX_GetOutputBufferStatus_Ptr = dlsym(handle, "SECDMX_GetOutputBufferStatus");
   SECDMX_ProcessData_Ptr = dlsym(handle, "SECDMX_ProcessData");
 
-  return 0;
+  return handle;
+}
+
+static int unload_secdmx_api(void)
+{
+  int ret=0;
+  if (secdmx_handle == NULL) {
+    return 0;
+  }
+  ret = dlclose(secdmx_handle);
+  secdmx_handle = NULL;
+  return ret;
 }
 
 int add_dvr_pids(Record_DeviceContext_t *p_ctx)
@@ -121,7 +132,7 @@
     for (i = 0; i < DVR_MAX_RECORD_PIDS_COUNT; i++) {
       if (p_ctx->streams[i].pid != DVR_INVALID_PID) {
         pids[cnt++] = p_ctx->streams[i].pid;
-        DVR_DEBUG(0, "dvr pid:%#x, cnt:%#x", pids[cnt-1], cnt);
+        DVR_DEBUG("dvr pid:%x, cnt:%x", pids[cnt-1], cnt);
       }
     }
     if (SECDMX_AddDVRPids_Ptr != NULL && p_ctx->output_handle)
@@ -166,14 +177,19 @@
   p_ctx->fd = open(dev_name, O_RDONLY);
   if (p_ctx->fd == -1)
   {
-    DVR_DEBUG(1, "%s cannot open \"%s\" (%s)", __func__, dev_name, strerror(errno));
+    DVR_INFO("%s cannot open \"%s\" (%s)", __func__, dev_name, strerror(errno));
     pthread_mutex_unlock(&p_ctx->lock);
     return DVR_FAILURE;
   }
-  fcntl(p_ctx->fd, F_SETFL, fcntl(p_ctx->fd, F_GETFL, 0) | O_NONBLOCK, 0);
+  if (fcntl(p_ctx->fd, F_SETFL, fcntl(p_ctx->fd, F_GETFL, 0) | O_NONBLOCK, 0) < 0) {
+    DVR_ERROR("%s setting non-block flag fails with errno:%d(%s)",
+        __func__,errno,strerror(errno));
+    pthread_mutex_unlock(&p_ctx->lock);
+    return DVR_FAILURE;
+  }
 
   p_ctx->evtfd = eventfd(0, 0);
-  DVR_DEBUG(1, "%s, %d fd: %d %p %d %p", __func__, __LINE__, p_ctx->fd, &(p_ctx->fd), p_ctx->evtfd, &(p_ctx->evtfd));
+  DVR_INFO("%s, %d fd: %d %p %d %p", __func__, __LINE__, p_ctx->fd, &(p_ctx->fd), p_ctx->evtfd, &(p_ctx->evtfd));
   load_secdmx_api();
   /*Configure flush size*/
   if (dvr_check_dmx_isNew() == 1) {
@@ -181,27 +197,20 @@
     if (SECDMX_Init_Ptr != NULL) {
       ret = SECDMX_Init_Ptr();
       if (ret != DVR_SUCCESS) {
-        DVR_DEBUG(1, "%s secure demux init failed:%d", __func__, ret);
+        DVR_INFO("%s secure demux init failed:%d", __func__, ret);
       }
     }
-
-    //set buf size
-    int buf_size = params->buf_size;
-    ret = ioctl(p_ctx->fd, DMX_SET_BUFFER_SIZE, buf_size);
-    if (ret == -1) {
-      DVR_DEBUG(1, "%s set dvr buf size failed\"%s\" (%s) buf_size:%d", __func__, dev_name, strerror(errno), buf_size);
-    } else {
-      DVR_DEBUG(1, "%s set dvr buf size success \"%s\" buf_size:%d", __func__, dev_name, buf_size);
-    }
-  } else {
+  }
+  //set dvbcore ringbuf size
+  {
       //set del buf size is 10 * 188 *1024
       int buf_size = params->ringbuf_size;
       if (buf_size > 0) {
           ret = ioctl(p_ctx->fd, DMX_SET_BUFFER_SIZE, buf_size);
           if (ret == -1) {
-            DVR_DEBUG(1, "%s set dvr ringbuf size failed\"%s\" (%s) buf_size:%d", __func__, dev_name, strerror(errno), buf_size);
+            DVR_INFO("%s set dvr ringbuf size failed\"%s\" (%s) buf_size:%d", __func__, dev_name, strerror(errno), buf_size);
           } else {
-            DVR_DEBUG(1, "%s set dvr ringbuf size success \"%s\" buf_size:%d", __func__, dev_name, buf_size);
+            DVR_INFO("%s set dvr ringbuf size success \"%s\" buf_size:%d", __func__, dev_name, buf_size);
           }
       }
   }
@@ -234,8 +243,8 @@
   dvr_file_echo(buf, "0");
 
   if (params->fend_dev_id > MAX_FEND_DEVICE_COUNT -1) {
-    DVR_DEBUG(0, "invalid frontend devicie id:%d, will use default.\n",
-	      params->fend_dev_id);
+    DVR_ERROR("invalid frontend device id:%d, will use default.\n",
+          params->fend_dev_id);
     p_ctx->fend_dev_id = 0;
   } else {
     p_ctx->fend_dev_id = params->fend_dev_id;
@@ -274,23 +283,26 @@
     }
     if (p_ctx->dvr_buf) {
       if (SECDMX_FreeDVRBuffer_Ptr != NULL) {
-	for (i = 0; i < MAX_RECORD_DEVICE_COUNT; i++) {
-	  if (&record_ctx[i] != p_ctx &&
-	      record_ctx[i].fend_dev_id == p_ctx->fend_dev_id &&
-	      record_ctx[i].dvr_buf == p_ctx->dvr_buf) {
-		break;
-	  }
-	}
-	if (i >= MAX_RECORD_DEVICE_COUNT) {
+    for (i = 0; i < MAX_RECORD_DEVICE_COUNT; i++) {
+      if (&record_ctx[i] != p_ctx &&
+          record_ctx[i].fend_dev_id == p_ctx->fend_dev_id &&
+          record_ctx[i].dvr_buf == p_ctx->dvr_buf) {
+        break;
+      }
+    }
+    if (i >= MAX_RECORD_DEVICE_COUNT) {
           SECDMX_FreeDVRBuffer_Ptr(p_ctx->fend_dev_id);
-	}
-	p_ctx->dvr_buf = (size_t)NULL;
+    }
+    p_ctx->dvr_buf = (size_t)NULL;
       }
     }
   }
   p_ctx->fend_dev_id = -1;
   p_ctx->state = RECORD_DEVICE_STATE_CLOSED;
   pthread_mutex_unlock(&p_ctx->lock);
+
+  unload_secdmx_api();
+
   return DVR_SUCCESS;
 }
 
@@ -323,22 +335,27 @@
   DVR_RETURN_IF_FALSE_WITH_UNLOCK(p_ctx->streams[i].pid == DVR_INVALID_PID, &p_ctx->lock);
 
   p_ctx->streams[i].pid = pid;
-  DVR_DEBUG(1, "%s add pid:%#x", __func__, pid);
-	snprintf(dev_name, sizeof(dev_name), "/dev/dvb0.demux%d", p_ctx->dmx_dev_id);
+  DVR_INFO("%s add pid:%#x", __func__, pid);
+    snprintf(dev_name, sizeof(dev_name), "/dev/dvb0.demux%d", p_ctx->dmx_dev_id);
   fd = open(dev_name, O_RDWR);
   if (fd == -1) {
-    DVR_DEBUG(1, "%s cannot open \"%s\" (%s)", __func__, dev_name, strerror(errno));
+    DVR_INFO("%s cannot open \"%s\" (%s)", __func__, dev_name, strerror(errno));
     pthread_mutex_unlock(&p_ctx->lock);
     return DVR_FAILURE;
   }
-  //DVR_DEBUG(1, "%s libdvrFilterTrace open1 \"%s\" p_ctx->dmx_dev_id: 0x%x, fd: 0x%x ", __func__,dev_name,p_ctx->dmx_dev_id, fd);
+  //DVR_INFO("%s libdvrFilterTrace open1 \"%s\" p_ctx->dmx_dev_id: 0x%x, fd: 0x%x ", __func__,dev_name,p_ctx->dmx_dev_id, fd);
   p_ctx->streams[i].fid = fd;
 
   //DVR_RETURN_IF_FALSE_WITH_UNLOCK(DVR_SUCCESS == add_dvr_pids(p_ctx), &p_ctx->lock);
   add_dvr_pids(p_ctx);
   if (p_ctx->state == RECORD_DEVICE_STATE_STARTED) {
     //need start pid filter
-    fcntl(fd, F_SETFL, O_NONBLOCK);
+    if (fcntl(fd, F_SETFL, O_NONBLOCK)<0) {
+      DVR_ERROR("%s setting non-block flag fails with errno:%d(%s)",
+          __func__,errno,strerror(errno));
+      pthread_mutex_unlock(&p_ctx->lock);
+      return DVR_FAILURE;
+    }
     memset(&params, 0, sizeof(params));
     params.pid = p_ctx->streams[i].pid;
     params.input = DMX_IN_FRONTEND;
@@ -346,13 +363,13 @@
     params.pes_type = DMX_PES_OTHER;
     ret = ioctl(fd, DMX_SET_PES_FILTER, &params);
     if (ret == -1) {
-      DVR_DEBUG(1, "%s set pes filter failed\"%s\" (%s)", __func__, dev_name, strerror(errno));
+      DVR_INFO("%s set pes filter failed\"%s\" (%s)", __func__, dev_name, strerror(errno));
       pthread_mutex_unlock(&p_ctx->lock);
       return DVR_FAILURE;
     }
     ret = ioctl(fd, DMX_START, 0);
     if (ret == -1) {
-      DVR_DEBUG(1, "%s start pes filter failed:\"%s\" (%s)", __func__, dev_name, strerror(errno));
+      DVR_INFO("%s start pes filter failed:\"%s\" (%s)", __func__, dev_name, strerror(errno));
       pthread_mutex_unlock(&p_ctx->lock);
       return DVR_FAILURE;
     }
@@ -394,7 +411,7 @@
   if (p_ctx->streams[i].is_start == DVR_TRUE) {
     ret = ioctl(fd, DMX_STOP, 0);
     if (ret == -1) {
-      DVR_DEBUG(1, "%s stop pes filter failed (%s)", __func__, strerror(errno));
+      DVR_INFO("%s stop pes filter failed (%s)", __func__, strerror(errno));
       pthread_mutex_unlock(&p_ctx->lock);
       return DVR_FAILURE;
     }
@@ -403,7 +420,7 @@
   p_ctx->streams[i].pid = DVR_INVALID_PID;
   //DVR_RETURN_IF_FALSE_WITH_UNLOCK(DVR_SUCCESS == add_dvr_pids(p_ctx), &p_ctx->lock);
   add_dvr_pids(p_ctx);
-  //DVR_DEBUG(1, "%s libdvrFilterTrace close1-1. pid: 0x%x, fd: 0x%x ", __func__,pid, fd);
+  //DVR_INFO("%s libdvrFilterTrace close1-1. pid: 0x%x, fd: 0x%x ", __func__,pid, fd);
   close(fd);
   p_ctx->streams[i].fid = -1;
   p_ctx->streams[i].is_start = DVR_FALSE;
@@ -432,7 +449,7 @@
   if (p_ctx->state != RECORD_DEVICE_STATE_OPENED &&
       p_ctx->state != RECORD_DEVICE_STATE_STOPPED) {
     pthread_mutex_unlock(&p_ctx->lock);
-    DVR_DEBUG(1, "%s, %d, wrong state:%d", __func__, __LINE__,p_ctx->state);
+    DVR_ERROR("%s, %d, wrong state:%d", __func__, __LINE__,p_ctx->state);
     return DVR_FAILURE;
   }
 
@@ -445,7 +462,12 @@
         p_ctx->streams[i].is_start == DVR_FALSE) {
       //need start pid filter
       fd = p_ctx->streams[i].fid;
-      fcntl(fd, F_SETFL, O_NONBLOCK);
+      if (fcntl(fd, F_SETFL, O_NONBLOCK)<0) {
+          DVR_ERROR("%s setting non-block flag fails with errno:%d(%s)",
+              __func__,errno,strerror(errno));
+          pthread_mutex_unlock(&p_ctx->lock);
+          return DVR_FAILURE;
+      }
       memset(&params, 0, sizeof(params));
       params.pid = p_ctx->streams[i].pid;
       params.input = DMX_IN_FRONTEND;
@@ -453,13 +475,13 @@
       params.pes_type = DMX_PES_OTHER;
       ret = ioctl(fd, DMX_SET_PES_FILTER, &params);
       if (ret == -1) {
-        DVR_DEBUG(1, "%s set pes filter failed (%s)", __func__, strerror(errno));
+        DVR_ERROR("%s set pes filter failed (%s)", __func__, strerror(errno));
         pthread_mutex_unlock(&p_ctx->lock);
         return DVR_FAILURE;
       }
       ret = ioctl(fd, DMX_START, 0);
       if (ret == -1) {
-        DVR_DEBUG(1, "%s start pes filter failed (%s)", __func__, strerror(errno));
+        DVR_ERROR("%s start pes filter failed (%s)", __func__, strerror(errno));
         pthread_mutex_unlock(&p_ctx->lock);
         return DVR_FAILURE;
       }
@@ -489,7 +511,7 @@
 
   pthread_mutex_lock(&p_ctx->lock);
   if (p_ctx->state != RECORD_DEVICE_STATE_STARTED) {
-    DVR_DEBUG(1, "%s, %d, wrong state:%d", __func__, __LINE__,p_ctx->state);
+    DVR_INFO("%s, %d, wrong state:%d", __func__, __LINE__,p_ctx->state);
     pthread_mutex_unlock(&p_ctx->lock);
     return DVR_FAILURE;
   }
@@ -502,13 +524,13 @@
       fd = p_ctx->streams[i].fid;
       ret = ioctl(fd, DMX_STOP, 0);
       if (ret == -1) {
-        DVR_DEBUG(1, "%s stop pes filter failed (%s)", __func__, strerror(errno));
+        DVR_INFO("%s stop pes filter failed (%s)", __func__, strerror(errno));
         pthread_mutex_unlock(&p_ctx->lock);
         return DVR_FAILURE;
       }
       /*Close the filter*/
       p_ctx->streams[i].pid = DVR_INVALID_PID;
-      //DVR_DEBUG(1, "%s libdvrFilterTrace close1-2. fd: 0x%x ", __func__, fd);
+      //DVR_INFO("%s libdvrFilterTrace close1-2. fd: 0x%x ", __func__, fd);
       close(fd);
       p_ctx->streams[i].fid = -1;
       p_ctx->streams[i].is_start = DVR_FALSE;
@@ -547,7 +569,9 @@
   ret = poll(fds, 2, timeout);
   if (ret <= 0) {
     if (ret < 0)
-      DVR_DEBUG(1, "%s, %d failed: %s fd %d evfd %d", __func__, __LINE__, strerror(errno), p_ctx->fd, p_ctx->evtfd);
+      DVR_INFO("%s, %d failed: %s fd %d event fd %d", __func__, __LINE__, strerror(errno), p_ctx->fd, p_ctx->evtfd);
+    else
+      DVR_INFO("%s, %d timeout", __func__, __LINE__);
     return DVR_FAILURE;
   }
 
@@ -558,7 +582,7 @@
   if (p_ctx->state == RECORD_DEVICE_STATE_STARTED) {
     ret = read(fds[0].fd, buf, len);
     if (ret <= 0) {
-      DVR_DEBUG(1, "%s, %d failed: %s", __func__, __LINE__, strerror(errno));
+      DVR_INFO("%s, %d failed: %s", __func__, __LINE__, strerror(errno));
       pthread_mutex_unlock(&p_ctx->lock);
       return DVR_FAILURE;
     }
@@ -592,20 +616,20 @@
   pthread_mutex_lock(&secdmx_lock[sid]);
   memset(&info, 0, sizeof(info));
   result = ioctl(p_ctx->fd, DMX_GET_DVR_MEM, &info);
-  //DVR_DEBUG(1, "sid[%d] fd[%d] wp:%#x\n", sid, p_ctx->fd, info.wp_offset);
+  //DVR_INFO("sid[%d] fd[%d] wp:%#x\n", sid, p_ctx->fd, info.wp_offset);
   if (result == DVR_SUCCESS) {
     if (SECDMX_ProcessData_Ptr != NULL)
       result = SECDMX_ProcessData_Ptr(sid, info.wp_offset);
   }
   if (result) {
-    DVR_DEBUG(1, "result:%#x\n", result);
+    DVR_INFO("result:%#x\n", result);
   }
   pthread_mutex_unlock(&secdmx_lock[sid]);
 
   DVR_RETURN_IF_FALSE_WITH_UNLOCK(result == DVR_SUCCESS, &p_ctx->lock);
   if (SECDMX_GetOutputBufferStatus_Ptr != NULL)
     result = SECDMX_GetOutputBufferStatus_Ptr(p_ctx->output_handle, buf, len);
-  //DVR_DEBUG(1, "addr:%#x, len:%#x\n", *buf, *len);
+  //DVR_INFO("addr:%#x, len:%#x\n", *buf, *len);
   DVR_RETURN_IF_FALSE_WITH_UNLOCK(result == DVR_SUCCESS, &p_ctx->lock);
 
   pthread_mutex_unlock(&p_ctx->lock);
@@ -634,68 +658,73 @@
   pthread_mutex_lock(&p_ctx->lock);
   if (p_ctx->state != RECORD_DEVICE_STATE_OPENED &&
       p_ctx->state != RECORD_DEVICE_STATE_STOPPED) {
+    DVR_INFO("%s, %d, wrong state:%d", __func__, __LINE__,p_ctx->state);
     pthread_mutex_unlock(&p_ctx->lock);
-    DVR_DEBUG(1, "%s, %d, wrong state:%d", __func__, __LINE__,p_ctx->state);
     return DVR_FAILURE;
   }
 
   if (dvr_check_dmx_isNew() == 1) {
     //new dmx drive,used io to set sec buf.
-    int result;
-    size_t dvr_buf;
-    size_t op_handle;
+    int result = DVR_SUCCESS;
+    size_t dvr_buf = 0;
+    size_t op_handle = 0;
     int sid = p_ctx->fend_dev_id;
     int fd;
     char node[32] = {0};
     memset(node, 0, sizeof(node));
     snprintf(node, sizeof(node), "/dev/dvb0.demux%d", p_ctx->dmx_dev_id);
     fd = open(node, O_RDONLY);
-    //DVR_DEBUG(1, "%s libdvrFilterTrace open2 \"%s\",p_ctx->dmx_dev_id: 0x%x, fd: 0x%x ", __func__,node, p_ctx->dmx_dev_id, fd);
+    if (fd<0) {
+      DVR_ERROR("opening %d returns failure. errno:%d, %s", fd, errno, strerror(errno));
+      pthread_mutex_unlock(&p_ctx->lock);
+      return DVR_FAILURE;
+    }
+    //DVR_INFO("%s libdvrFilterTrace open2 \"%s\",p_ctx->dmx_dev_id: 0x%x, fd: 0x%x ", __func__,node, p_ctx->dmx_dev_id, fd);
     if (SECDMX_AllocateDVRBuffer_Ptr != NULL) {
-	for (i = 0; i < MAX_RECORD_DEVICE_COUNT; i++) {
-	  if (record_ctx[i].state != RECORD_DEVICE_STATE_CLOSED &&
-	      &record_ctx[i] != p_ctx &&
-	      record_ctx[i].fend_dev_id == p_ctx->fend_dev_id &&
-	      record_ctx[i].dvr_buf != 0) {
-		break;
-	  }
-	}
-	if (i >= MAX_RECORD_DEVICE_COUNT) {
-	  result = SECDMX_AllocateDVRBuffer_Ptr(sid, len, &dvr_buf);
-	  if (result != DVR_SUCCESS) {
-	  //DVR_DEBUG(1, "%s libdvrFilterTrace close2-1. fd: 0x%x ", __func__, fd);
-	     close(fd);
-	  }
-	  DVR_RETURN_IF_FALSE_WITH_UNLOCK(result == DVR_SUCCESS, &p_ctx->lock);
-	} else {
-	  dvr_buf = record_ctx[i].dvr_buf;
-	}
-
-	p_ctx->dvr_buf = dvr_buf;
+    for (i = 0; i < MAX_RECORD_DEVICE_COUNT; i++) {
+      if (record_ctx[i].state != RECORD_DEVICE_STATE_CLOSED &&
+          &record_ctx[i] != p_ctx &&
+          record_ctx[i].fend_dev_id == p_ctx->fend_dev_id &&
+          record_ctx[i].dvr_buf != 0) {
+        break;
+      }
+    }
+    if (i >= MAX_RECORD_DEVICE_COUNT) {
+      result = SECDMX_AllocateDVRBuffer_Ptr(sid, len, &dvr_buf);
+      if (result != DVR_SUCCESS) {
+      //DVR_INFO("%s libdvrFilterTrace close2-1. fd: 0x%x ", __func__, fd);
+         close(fd);
+      }
+      DVR_RETURN_IF_FALSE_WITH_UNLOCK(result == DVR_SUCCESS, &p_ctx->lock);
     } else {
-	p_ctx->dvr_buf = (size_t)sec_buf;
+      dvr_buf = record_ctx[i].dvr_buf;
+    }
+
+    p_ctx->dvr_buf = dvr_buf;
+    } else {
+    p_ctx->dvr_buf = (size_t)sec_buf;
     }
 
     struct dmx_sec_mem sec_mem;
     sec_mem.buff = p_ctx->dvr_buf;
     sec_mem.size = len;
     if (ioctl(fd, DMX_SET_SEC_MEM, &sec_mem) == -1) {
-      DVR_DEBUG(1, "record_device_set_secure_buffer ioctl DMX_SET_SEC_MEM error:%d", errno);
+      DVR_INFO("record_device_set_secure_buffer ioctl DMX_SET_SEC_MEM error:%d", errno);
     }
     else
     {
-      DVR_DEBUG(1, "record_device_set_secure_buffer ioctl sucesss DMX_SET_SEC_MEM: fd:%d, buf:%#x\n", fd, p_ctx->dvr_buf);
+      DVR_INFO("record_device_set_secure_buffer ioctl succeeded DMX_SET_SEC_MEM: fd:%d, buf:%#x\n", fd, p_ctx->dvr_buf);
     }
     if (SECDMX_AddOutputBuffer_Ptr != NULL)
       result = SECDMX_AddOutputBuffer_Ptr(sid, (size_t)sec_buf, len, &op_handle);
     if (result != DVR_SUCCESS) {
-    //DVR_DEBUG(1, "%s libdvrFilterTrace close2-2. fd: 0x%x ", __func__, fd);
+    //DVR_INFO("%s libdvrFilterTrace close2-2. fd: 0x%x ", __func__, fd);
       close(fd);
     }
     DVR_RETURN_IF_FALSE_WITH_UNLOCK(result == DVR_SUCCESS, &p_ctx->lock);
     p_ctx->output_handle = op_handle;
 
-    //DVR_DEBUG(1, "%s libdvrFilterTrace close2-3. fd: 0x%x ", __func__, fd);
+    //DVR_INFO("%s libdvrFilterTrace close2-3. fd: 0x%x ", __func__, fd);
     close(fd);
     pthread_mutex_unlock(&p_ctx->lock);
     return DVR_SUCCESS;
diff --git a/src/segment.c b/src/segment.c
index 3bd8938..80f4c8c 100644
--- a/src/segment.c
+++ b/src/segment.c
@@ -13,8 +13,12 @@
 #define MAX_SEGMENT_PATH_SIZE (DVR_MAX_LOCATION_SIZE + 32)
 #define MAX_PTS_THRESHOLD (10*1000)
 #define PCR_RECORD_INTERVAL_MS (300)
-#define PTS_DISCONTINE_DEVIATION     (40)
+#define PTS_DISCONTINUED_DEVIATION     (40)
 #define PTS_HEAD_DEVIATION     (40)
+#define PCR_JUMP_DUR     (5000)
+
+#define IDX_FILE_SYNC_TIME    (10)//10*PCR_RECORD_INTERVAL_MS
+#define TS_FILE_SYNC_TIME     (9)//9*PCR_RECORD_INTERVAL_MS
 
 
 /**\brief Segment context*/
@@ -22,7 +26,8 @@
   int             ts_fd;                              /**< Segment ts file fd*/
   FILE            *index_fp;                          /**< Time index file fd*/
   FILE            *dat_fp;                            /**< Information file fd*/
-  FILE            *ongoing_fp;                        /**< Ongoing file fd, used to verify timedhift mode*/
+  FILE            *all_dat_fp;                            /**< Information file fd*/
+  FILE            *ongoing_fp;                        /**< Ongoing file fd, used to verify timeshift mode*/
   uint64_t        first_pts;                          /**< First pts value, use for write mode*/
   uint64_t        last_pts;                           /**< Last input pts value, use for write mode*/
   uint64_t        last_record_pts;                    /**< Last record pts value, use for write mode*/
@@ -33,7 +38,9 @@
   loff_t          last_offset;
   loff_t          last_record_offset;
   float           avg_rate;
-} Segment_Context_t;
+  int             time;
+  DVR_Bool_t      force_sysclock;                     /**< If ture, force to use system clock as PVR index time source. If false, libdvr can determine index time source based on actual situation*/
+ } Segment_Context_t;
 
 /**\brief Segment file type*/
 typedef enum {
@@ -41,6 +48,7 @@
   SEGMENT_FILE_TYPE_INDEX,                    /**< Used for store index data*/
   SEGMENT_FILE_TYPE_DAT,                      /**< Used for store information data, such as duration etc*/
   SEGMENT_FILE_TYPE_ONGOING,                  /**< Used for store information data, such as duration etc*/
+  SEGMENT_FILE_TYPE_ALL_DATA,                  /**< Used for store all information data*/
 } Segment_FileType_t;
 
 static void segment_get_fname(char fname[MAX_SEGMENT_PATH_SIZE],
@@ -50,21 +58,30 @@
 {
   int offset;
 
-  memset(fname, 0, MAX_SEGMENT_PATH_SIZE);
-  strncpy(fname, location, strlen(location));
   offset = strlen(location);
-  strncpy(fname + offset, "-", 1);
-  offset += 1;
-  sprintf(fname + offset, "%04llu", segment_id);
-  offset += 4;
+  DVR_ASSERT(offset < DVR_MAX_LOCATION_SIZE);
+
+  memset(fname, 0, MAX_SEGMENT_PATH_SIZE);
+  strncpy(fname, location, offset);
+
+  if (type != SEGMENT_FILE_TYPE_ALL_DATA) {
+    strncpy(fname + offset, "-", 2);
+    offset += 1;
+    sprintf(fname + offset, "%04llu", segment_id);
+    offset += strlen(fname + offset);
+  }
+
   if (type == SEGMENT_FILE_TYPE_TS)
-    strncpy(fname + offset, ".ts", 3);
+    strncpy(fname + offset, ".ts", 4);
   else if (type == SEGMENT_FILE_TYPE_INDEX)
-    strncpy(fname + offset, ".idx", 4);
+    strncpy(fname + offset, ".idx", 5);
   else if (type == SEGMENT_FILE_TYPE_DAT)
-    strncpy(fname + offset, ".dat", 4);
+    strncpy(fname + offset, ".dat", 5);
   else if (type == SEGMENT_FILE_TYPE_ONGOING)
-    strncpy(fname + offset, ".going", 6);
+    strncpy(fname + offset, ".going", 7);
+  else if (type == SEGMENT_FILE_TYPE_ALL_DATA)
+    strncpy(fname + offset, ".dat", 5);
+
 }
 
 static void segment_get_dirname(char dir_name[MAX_SEGMENT_PATH_SIZE],
@@ -90,13 +107,15 @@
   char ts_fname[MAX_SEGMENT_PATH_SIZE];
   char index_fname[MAX_SEGMENT_PATH_SIZE];
   char dat_fname[MAX_SEGMENT_PATH_SIZE];
+  char all_dat_fname[MAX_SEGMENT_PATH_SIZE];
   char dir_name[MAX_SEGMENT_PATH_SIZE];
   char going_name[MAX_SEGMENT_PATH_SIZE];
+  int ret = 0;
 
   DVR_RETURN_IF_FALSE(params);
   DVR_RETURN_IF_FALSE(p_handle);
 
-  //DVR_DEBUG(1, "%s, location:%s, id:%llu", __func__, params->location, params->segment_id);
+  //DVR_INFO("%s, location:%s, id:%llu", __func__, params->location, params->segment_id);
 
   p_ctx = (void*)malloc(sizeof(Segment_Context_t));
   DVR_RETURN_IF_FALSE(p_ctx);
@@ -111,14 +130,25 @@
   memset(dat_fname, 0, sizeof(dat_fname));
   segment_get_fname(dat_fname, params->location, params->segment_id, SEGMENT_FILE_TYPE_DAT);
 
+  memset(all_dat_fname, 0, sizeof(all_dat_fname));
+  segment_get_fname(all_dat_fname, params->location, params->segment_id, SEGMENT_FILE_TYPE_ALL_DATA);
+
+
   memset(going_name, 0, sizeof(going_name));
   segment_get_fname(going_name, params->location, params->segment_id, SEGMENT_FILE_TYPE_ONGOING);
 
   memset(dir_name, 0, sizeof(dir_name));
   segment_get_dirname(dir_name, params->location);
+
+  ret = mkdir(dir_name, 0666);
+  if (ret == -1) {
+    DVR_WARN("mkdir of %s returns %d due to errno:%d,%s",
+        dir_name,ret,errno,strerror(errno));
+  }
   if (access(dir_name, F_OK) == -1) {
-    DVR_DEBUG(1, "%s dir %s is not exist, create it", __func__, dir_name);
-    mkdir(dir_name, 0666);
+    DVR_ERROR("%s dir %s does not exist", __func__, dir_name);
+    free(p_ctx);
+    return DVR_FAILURE;
   }
 
   if (params->mode == SEGMENT_MODE_READ) {
@@ -126,25 +156,29 @@
     p_ctx->index_fp = fopen(index_fname, "r");
     p_ctx->dat_fp = fopen(dat_fname, "r");
     p_ctx->ongoing_fp = NULL;
+    p_ctx->all_dat_fp = fopen(all_dat_fname, "r");
   } else if (params->mode == SEGMENT_MODE_WRITE) {
     p_ctx->ts_fd = open(ts_fname, O_CREAT | O_RDWR | O_TRUNC, 0644);
     p_ctx->index_fp = fopen(index_fname, "w+");
     p_ctx->dat_fp = fopen(dat_fname, "w+");
+    p_ctx->all_dat_fp = fopen(all_dat_fname, "a+");
+    DVR_INFO("%s dir %s is opened", __func__, all_dat_fname);
     p_ctx->ongoing_fp = fopen(going_name, "w+");
     p_ctx->first_pts = ULLONG_MAX;
     p_ctx->last_pts = ULLONG_MAX;
     p_ctx->last_record_pts = ULLONG_MAX;
     p_ctx->avg_rate = 0.0;
   } else {
-    DVR_DEBUG(1, "%s, unknow mode use default", __func__);
+    DVR_INFO("%s, unknown mode use default", __func__);
     p_ctx->ts_fd = open(ts_fname, O_RDONLY);
     p_ctx->index_fp = fopen(index_fname, "r");
     p_ctx->dat_fp = fopen(dat_fname, "r");
+    p_ctx->all_dat_fp = fopen(all_dat_fname, "r");
     p_ctx->ongoing_fp = NULL;
   }
 
   if (p_ctx->ts_fd == -1 || !p_ctx->index_fp || !p_ctx->dat_fp) {
-    DVR_DEBUG(1, "%s open file failed [%s, %s, %s], reason:%s", __func__,
+    DVR_INFO("%s open file failed [%s, %s, %s], reason:%s", __func__,
         ts_fname, index_fname, dat_fname, strerror(errno));
     if (p_ctx->ts_fd != -1)
       close(p_ctx->ts_fd);
@@ -152,6 +186,8 @@
       fclose(p_ctx->index_fp);
     if (p_ctx->dat_fp)
       fclose(p_ctx->dat_fp);
+    if (p_ctx->all_dat_fp)
+      fclose(p_ctx->all_dat_fp);
     if (p_ctx->ongoing_fp)
       fclose(p_ctx->ongoing_fp);
     free(p_ctx);
@@ -159,9 +195,10 @@
     return DVR_FAILURE;
   }
   p_ctx->segment_id = params->segment_id;
-  strncpy(p_ctx->location, params->location, strlen(params->location));
+  strncpy(p_ctx->location, params->location, strlen(params->location)+1);
+  p_ctx->force_sysclock = params->force_sysclock;
 
-  //DVR_DEBUG(1, "%s, open file success p_ctx->location [%s]", __func__, p_ctx->location, params->mode);
+  //DVR_INFO("%s, open file success p_ctx->location [%s]", __func__, p_ctx->location, params->mode);
   *p_handle = (Segment_Handle_t)p_ctx;
   return DVR_SUCCESS;
 }
@@ -184,13 +221,15 @@
   if (p_ctx->dat_fp) {
     fclose(p_ctx->dat_fp);
   }
-
+  if (p_ctx->all_dat_fp) {
+    fclose(p_ctx->all_dat_fp);
+  }
   if (p_ctx->ongoing_fp != NULL) {
     fclose(p_ctx->ongoing_fp);
     char going_name[MAX_SEGMENT_PATH_SIZE];
     memset(going_name, 0, sizeof(going_name));
     segment_get_fname(going_name, p_ctx->location, p_ctx->segment_id, SEGMENT_FILE_TYPE_ONGOING);
-    DVR_DEBUG(1, "segment close del [%s]", going_name);
+    DVR_INFO("segment close del [%s]", going_name);
     unlink(going_name);
   }
 
@@ -219,7 +258,8 @@
   DVR_RETURN_IF_FALSE(buf);
   DVR_RETURN_IF_FALSE(p_ctx->ts_fd != -1);
   len = write(p_ctx->ts_fd, buf, count);
-  fsync(p_ctx->ts_fd);
+  if (p_ctx->time % TS_FILE_SYNC_TIME == 0)
+    fsync(p_ctx->ts_fd);
   return len;
 }
 
@@ -234,7 +274,7 @@
   DVR_RETURN_IF_FALSE(p_ctx->index_fp);
 
   if (p_ctx->first_pts == ULLONG_MAX) {
-    DVR_DEBUG(1, "%s first pcr:%llu", __func__, pts);
+    DVR_INFO("%s first pcr:%llu", __func__, pts);
     p_ctx->first_pts = pts;
     p_ctx->first_offset = offset;
   }
@@ -243,13 +283,13 @@
     /*Last pts is init value*/
     sprintf(buf, "{time=%llu, offset=%lld}", pts - p_ctx->first_pts, offset);
     p_ctx->cur_time = pts - p_ctx->first_pts;
-    DVR_DEBUG(1, "%s force pcr:%llu -1", __func__, pts);
+    DVR_INFO("%s force pcr:%llu -1", __func__, pts);
   } else {
     /*Last pts has valid value*/
     int diff = pts - p_ctx->last_pts;
     if ((diff > MAX_PTS_THRESHOLD) || (diff < 0)) {
       /*Current pts has a transition*/
-      DVR_DEBUG(1, "[%s]force update Current pts has a transition, [%llu, %llu, %llu]",__func__,
+      DVR_INFO("[%s]force update Current pts has a transition, [%llu, %llu, %llu]",__func__,
           p_ctx->first_pts, p_ctx->last_pts, pts);
       sprintf(buf, "\n{time=%llu, offset=%lld}", p_ctx->cur_time, offset);
     } else {
@@ -257,14 +297,14 @@
       //check if this pcr is transition.if true,add 200ms
       //other case normal.
       p_ctx->cur_time += diff;
-      DVR_DEBUG(1, "%s force pcr:%llu -1 diff [%d]", __func__, pts, diff);
+      DVR_INFO("%s force pcr:%llu -1 diff [%d]", __func__, pts, diff);
       sprintf(buf, "\n{time=%llu, offset=%lld}", p_ctx->cur_time, offset);
     }
   }
 
   record_diff = pts - p_ctx->last_record_pts;
   if (strlen(buf) > 0) {
-    DVR_DEBUG(1, "%s force pcr:%llu buf:%s", __func__, pts, buf);
+    DVR_INFO("%s force pcr:%llu buf:%s", __func__, pts, buf);
     fputs(buf, p_ctx->index_fp);
     fflush(p_ctx->index_fp);
     fsync(fileno(p_ctx->index_fp));
@@ -285,7 +325,7 @@
   DVR_RETURN_IF_FALSE(p_ctx->index_fp);
 
   if (p_ctx->first_pts == ULLONG_MAX) {
-    DVR_DEBUG(1, "%s first pcr:%llu", __func__, pts);
+    DVR_INFO("%s first pcr:%llu", __func__, pts);
     p_ctx->first_pts = pts;
     //p_ctx->cur_time = p_ctx->cur_time + PTS_HEAD_DEVIATION;
   }
@@ -295,34 +335,42 @@
     sprintf(buf, "{time=%llu, offset=%lld}", pts - p_ctx->first_pts, offset);
     p_ctx->cur_time = pts - p_ctx->first_pts;
   } else {
-    /*Last pts has valid value*/
-    int diff = pts - p_ctx->last_pts;
-    if ((diff > MAX_PTS_THRESHOLD) || (diff < 0)) {
-      /*Current pts has a transition*/
-      DVR_DEBUG(1, "Current pts has a transition, [%llu, %llu, %llu]",
-          p_ctx->first_pts, p_ctx->last_pts, pts);
-      p_ctx->last_record_pts = pts;
-      //p_ctx->cur_time = p_ctx->cur_time + PTS_DISCONTINE_DEVIATION;
-    } else {
-      /*This is a normal pts, record it*/
-      loff_t off_diff = offset - p_ctx->last_offset;
-      float rate = (float) (off_diff) / (float)(diff);
-      if (p_ctx->avg_rate == 0.0) {
-            p_ctx->avg_rate = (float) offset / (float)(p_ctx->cur_time + diff);
-      }
-      if (diff >= 1000) {
-        DVR_DEBUG(1, "PTS TRANSITION ERROR last pcr[%llu]pts[%llu]pcr diff[%d]off[%llu]off_diff[%llu]rate[%f]avg rate[%f]4*rate[%d]av_diff[%d]",p_ctx->last_pts, pts, diff, offset,off_diff, rate, p_ctx->avg_rate, (int)(rate * 4), (int)(off_diff / p_ctx->avg_rate));
-        if (p_ctx->avg_rate != 0 && (int)(p_ctx->avg_rate) >= (int)(rate * 4)) {
-          diff = off_diff / p_ctx->avg_rate;
-          p_ctx->cur_time += diff;
-        } else {
-          p_ctx->cur_time += diff;
-        }
+    if (!p_ctx->force_sysclock) {
+      /* if force_sysclock is off, we follow old manner. Please refer to
+       * SWPL-75327*/
+      /*Last pts has valid value*/
+      int diff = pts - p_ctx->last_pts;
+      if ((diff > MAX_PTS_THRESHOLD) || (diff < 0)) {
+        /*Current pts has a transition*/
+        DVR_INFO("Current pts has a transition, [%llu, %llu, %llu]",
+            p_ctx->first_pts, p_ctx->last_pts, pts);
+        p_ctx->last_record_pts = pts;
+        //p_ctx->cur_time = p_ctx->cur_time + PTS_DISCONTINUED_DEVIATION;
       } else {
-         p_ctx->cur_time += diff;
+        /*This is a normal pts, record it*/
+        loff_t off_diff = offset - p_ctx->last_offset;
+        float rate = (float) (off_diff) / (float)(diff);
+        if (p_ctx->avg_rate == 0.0) {
+              p_ctx->avg_rate = (float) offset / (float)(p_ctx->cur_time + diff);
+        }
+        if (diff >= PCR_JUMP_DUR) {
+          DVR_INFO("PTS TRANSITION ERROR last pcr[%llu]pts[%llu]pcr diff[%d]off[%llu]off_diff[%llu]rate[%f]avg rate[%f]4*rate[%d]av_diff[%d]",p_ctx->last_pts, pts, diff, offset,off_diff, rate, p_ctx->avg_rate, (int)(rate * 4), (int)(off_diff / p_ctx->avg_rate));
+          if (p_ctx->avg_rate != 0 && (int)(p_ctx->avg_rate) >= (int)(rate * 4)) {
+            diff = off_diff / p_ctx->avg_rate;
+            p_ctx->cur_time += diff;
+          } else {
+            p_ctx->cur_time += diff;
+          }
+        } else {
+           p_ctx->cur_time += diff;
+        }
       }
-      sprintf(buf, "\n{time=%llu, offset=%lld}", p_ctx->cur_time, offset);
+    } else {
+      /* if force_sysclock is on, we simply calculate cur_time based on system
+       * time. Please refer to SWPL-75327*/
+      p_ctx->cur_time = pts - p_ctx->first_pts;
     }
+    sprintf(buf, "\n{time=%llu, offset=%lld}", p_ctx->cur_time, offset);
   }
 
   record_diff = pts - p_ctx->last_record_pts;
@@ -330,7 +378,12 @@
       (record_diff > PCR_RECORD_INTERVAL_MS || p_ctx->last_record_pts == ULLONG_MAX)){
     fputs(buf, p_ctx->index_fp);
     fflush(p_ctx->index_fp);
-    fsync(fileno(p_ctx->index_fp));
+    p_ctx->time++;
+    //flush idx file 3s
+    if ((p_ctx->time > 0 && p_ctx->time % IDX_FILE_SYNC_TIME == 0))
+      fsync(fileno(p_ctx->index_fp));
+    if (p_ctx->time > IDX_FILE_SYNC_TIME)
+      p_ctx->time = 0;
     p_ctx->last_record_pts = pts;
     p_ctx->last_record_offset = offset;
     if (p_ctx->cur_time > 0)
@@ -349,8 +402,9 @@
   uint64_t pts = 0L;
   loff_t offset = 0;
   char *p1, *p2;
+  int ret = 0;
 
-  DVR_DEBUG(1, "into seek time=%llu, offset=%lld time--%llu\n", pts, offset, time);
+  DVR_INFO("into seek time=%llu, offset=%lld time--%llu\n", pts, offset, time);
 
   p_ctx = (Segment_Context_t *)handle;
   DVR_RETURN_IF_FALSE(p_ctx);
@@ -359,13 +413,14 @@
 
   if (time == 0) {
     offset = 0;
-    DVR_DEBUG(1, "seek time=%llu, offset=%lld time--%llu\n", pts, offset, time);
+    DVR_INFO("seek time=%llu, offset=%lld time--%llu\n", pts, offset, time);
     DVR_RETURN_IF_FALSE(lseek(p_ctx->ts_fd, offset, SEEK_SET) != -1);
     return offset;
   }
 
   memset(buf, 0, sizeof(buf));
-  DVR_RETURN_IF_FALSE(fseek(p_ctx->index_fp, 0, SEEK_SET) != -1);
+  ret = fseek(p_ctx->index_fp, 0, SEEK_SET);
+  DVR_RETURN_IF_FALSE(ret != -1);
   int line = 0;
   while (fgets(buf, sizeof(buf), p_ctx->index_fp) != NULL) {
     line++;
@@ -388,15 +443,15 @@
     }
     if (0)
     {
-      DVR_DEBUG(1, "seek buf[%s]", buf);
-      DVR_DEBUG(1, "seek time=%llu, offset=%lld\n", pts, offset);
+      DVR_INFO("seek buf[%s]", buf);
+      DVR_INFO("seek time=%llu, offset=%lld\n", pts, offset);
     }
     memset(buf, 0, sizeof(buf));
     if (time <= pts) {
       if (block_size > 0) {
         offset = offset - offset%block_size;
       }
-      //DVR_DEBUG(1, "seek time=%llu, offset=%lld time--%llu line %d\n", pts, offset, time, line);
+      //DVR_INFO("seek time=%llu, offset=%lld time--%llu line %d\n", pts, offset, time, line);
       DVR_RETURN_IF_FALSE(lseek(p_ctx->ts_fd, offset, SEEK_SET) != -1);
       return offset;
     }
@@ -405,11 +460,11 @@
     if (block_size > 0) {
       offset = offset - offset%block_size;
     }
-    DVR_DEBUG(1, "seek time=%llu, offset=%lld time--%llu line %d end\n", pts, offset, time, line);
+    DVR_INFO("seek time=%llu, offset=%lld time--%llu line %d end\n", pts, offset, time, line);
     DVR_RETURN_IF_FALSE(lseek(p_ctx->ts_fd, offset, SEEK_SET) != -1);
     return offset;
   }
-  DVR_DEBUG(1, "seek error line [%d]", line);
+  DVR_INFO("seek error line [%d]", line);
   return DVR_FAILURE;
 }
 
@@ -424,7 +479,7 @@
   return pos;
 }
 
-uint64_t segment_tell_position_time(Segment_Handle_t handle, loff_t position)
+loff_t segment_tell_position_time(Segment_Handle_t handle, loff_t position)
 {
   Segment_Context_t *p_ctx;
   char buf[256];
@@ -435,6 +490,7 @@
   loff_t offset = 0;
   loff_t offset_p = 0;
   char *p1, *p2;
+  int ret2 = 0;
 
   p_ctx = (Segment_Context_t *)handle;
   DVR_RETURN_IF_FALSE(p_ctx);
@@ -442,7 +498,8 @@
   DVR_RETURN_IF_FALSE(p_ctx->ts_fd);
 
   memset(buf, 0, sizeof(buf));
-  DVR_RETURN_IF_FALSE(fseek(p_ctx->index_fp, 0, SEEK_SET) != -1);
+  ret2 = fseek(p_ctx->index_fp, 0, SEEK_SET);
+  DVR_RETURN_IF_FALSE(ret2 != -1);
   DVR_RETURN_IF_FALSE(position != -1);
 
   while (fgets(buf, sizeof(buf), p_ctx->index_fp) != NULL) {
@@ -465,23 +522,26 @@
     }
 
     memset(buf, 0, sizeof(buf));
-    //DVR_DEBUG(1, "tell cur time=%llu, offset=%lld, position=%lld\n", pts, offset, position);
+    //DVR_INFO("tell cur time=%llu, offset=%lld, position=%lld\n", pts, offset, position);
     if (position <= offset
         &&position >= offset_p
         && offset - offset_p > 0) {
+      // Tainted data issue originating from fgets seem false positive, so we
+      // just suppress it here.
+      // coverity[tainted_data]
       ret = pts_p + (pts - pts_p) * (position - offset_p) / (offset - offset_p);
-      //DVR_DEBUG(1, "tell cur time=%llu, pts_p = %llu, offset=%lld, position=%lld offset_p+%lld\n", pts, pts_p, offset, position, offset_p);
+      //DVR_INFO("tell cur time=%llu, pts_p = %llu, offset=%lld, position=%lld offset_p+%lld\n", pts, pts_p, offset, position, offset_p);
       return ret;
     }
     offset_p = offset;
     pts_p = pts;
   }
-  //DVR_DEBUG(1, "tell cur time=%llu, offset=%lld, position=%lld\n", pts, offset, position);
+  //DVR_INFO("tell cur time=%llu, offset=%lld, position=%lld\n", pts, offset, position);
   return pts;
 }
 
 
-uint64_t segment_tell_current_time(Segment_Handle_t handle)
+loff_t segment_tell_current_time(Segment_Handle_t handle)
 {
   Segment_Context_t *p_ctx;
   char buf[256];
@@ -489,6 +549,7 @@
   uint64_t pts = 0L;
   loff_t offset = 0, position = 0;
   char *p1, *p2;
+  int ret = 0;
 
   p_ctx = (Segment_Context_t *)handle;
   DVR_RETURN_IF_FALSE(p_ctx);
@@ -496,7 +557,8 @@
   DVR_RETURN_IF_FALSE(p_ctx->ts_fd);
 
   memset(buf, 0, sizeof(buf));
-  DVR_RETURN_IF_FALSE(fseek(p_ctx->index_fp, 0, SEEK_SET) != -1);
+  ret = fseek(p_ctx->index_fp, 0, SEEK_SET);
+  DVR_RETURN_IF_FALSE(ret != -1);
   position = lseek(p_ctx->ts_fd, 0, SEEK_CUR);
   DVR_RETURN_IF_FALSE(position != -1);
 
@@ -520,16 +582,16 @@
     }
 
     memset(buf, 0, sizeof(buf));
-    //DVR_DEBUG(1, "tell cur time=%llu, offset=%lld, position=%lld\n", pts, offset, position);
+    //DVR_INFO("tell cur time=%llu, offset=%lld, position=%lld\n", pts, offset, position);
     if (position <= offset) {
       return pts;
     }
   }
-  //DVR_DEBUG(1, "tell cur time=%llu, offset=%lld, position=%lld\n", pts, offset, position);
+  //DVR_INFO("tell cur time=%llu, offset=%lld, position=%lld\n", pts, offset, position);
   return pts;
 }
 
-uint64_t segment_tell_total_time(Segment_Handle_t handle)
+loff_t segment_tell_total_time(Segment_Handle_t handle)
 {
   Segment_Context_t *p_ctx;
   char buf[256];
@@ -539,6 +601,7 @@
   loff_t offset = 0, position = 0;
   char *p1, *p2;
   int line = 0;
+  int ret = 0;
 
   p_ctx = (Segment_Context_t *)handle;
   DVR_RETURN_IF_FALSE(p_ctx);
@@ -550,15 +613,15 @@
   position = lseek(p_ctx->ts_fd, 0, SEEK_CUR);
   DVR_RETURN_IF_FALSE(position != -1);
 
-  //DVR_RETURN_IF_FALSE(fseek(p_ctx->index_fp, -1000L, SEEK_END) != -1);
-  //if seek error.we need seek 0 pos.
+  // if unable to seek from end, it is necessary to seek to file beginning position.
   if (fseek(p_ctx->index_fp, -1000L, SEEK_END) == -1) {
-    fseek(p_ctx->index_fp, 0L, SEEK_SET);
+    ret = fseek(p_ctx->index_fp, 0L, SEEK_SET);
+    DVR_RETURN_IF_FALSE(ret != -1);
   }
   /* Save last line buffer */
   while (fgets(buf, sizeof(buf), p_ctx->index_fp) != NULL) {
     if (strlen(buf) <= 0) {
-      DVR_DEBUG(1, "read index buf is len 0");
+      DVR_INFO("read index buf is len 0");
       continue;
     }
     memset(last_buf, 0, sizeof(last_buf));
@@ -586,7 +649,7 @@
     offset = strtoull(value, NULL, 10);
   }
   //if (line < 2)
-  //DVR_DEBUG(1, "totle time=%llu, offset=%lld, position=%lld, line:%d\n", pts, offset, position, line);
+  //DVR_INFO("totle time=%llu, offset=%lld, position=%lld, line:%d\n", pts, offset, position, line);
   return (pts == ULLONG_MAX ? DVR_FAILURE : pts);
 }
 
@@ -596,13 +659,15 @@
   Segment_Context_t *p_ctx;
   char buf[256];
   uint32_t i;
+  int ret = 0;
 
   p_ctx = (Segment_Context_t *)handle;
   DVR_RETURN_IF_FALSE(p_ctx);
   DVR_RETURN_IF_FALSE(p_ctx->dat_fp);
   DVR_RETURN_IF_FALSE(p_info);
-  //seek 0, rewrite info
-  DVR_RETURN_IF_FALSE(fseek(p_ctx->dat_fp, 0, SEEK_SET) != -1);
+  // seek to 0 to rewrite info
+  ret = fseek(p_ctx->dat_fp, 0, SEEK_SET);
+  DVR_RETURN_IF_FALSE(ret != -1);
 
   /*Save segment id*/
   memset(buf, 0, sizeof(buf));
@@ -623,7 +688,7 @@
 
   /*Save segment duration*/
   memset(buf, 0, sizeof(buf));
-  DVR_DEBUG(1, "duration store:[%ld]", p_info->duration);
+  DVR_INFO("duration store:[%ld]", p_info->duration);
   sprintf(buf, "duration=%ld\n", p_info->duration);
   fputs(buf, p_ctx->dat_fp);
 
@@ -643,6 +708,61 @@
 }
 
 /* Should consider the case of cut power, todo... */
+int segment_store_allInfo(Segment_Handle_t handle, Segment_StoreInfo_t *p_info)
+{
+  Segment_Context_t *p_ctx;
+  char buf[256];
+  uint32_t i;
+  int ret = 0;
+
+  p_ctx = (Segment_Context_t *)handle;
+  DVR_RETURN_IF_FALSE(p_ctx);
+  DVR_RETURN_IF_FALSE(p_ctx->all_dat_fp);
+  DVR_RETURN_IF_FALSE(p_info);
+
+  //seek to end to append info
+  ret = fseek(p_ctx->all_dat_fp, 0, SEEK_END);
+  DVR_RETURN_IF_FALSE(ret != -1);
+
+  /*Save segment id*/
+  memset(buf, 0, sizeof(buf));
+  sprintf(buf, "id=%lld\n", p_info->id);
+  fputs(buf, p_ctx->all_dat_fp);
+
+  /*Save number of pids*/
+  memset(buf, 0, sizeof(buf));
+  sprintf(buf, "nb_pids=%d\n", p_info->nb_pids);
+  fputs(buf, p_ctx->all_dat_fp);
+
+  /*Save pid information*/
+  for (i = 0; i < p_info->nb_pids; i++) {
+    memset(buf, 0, sizeof(buf));
+    sprintf(buf, "{pid=%d, type=%d}\n", p_info->pids[i].pid, p_info->pids[i].type);
+    fputs(buf, p_ctx->all_dat_fp);
+  }
+
+  /*Save segment duration*/
+  memset(buf, 0, sizeof(buf));
+  DVR_INFO("duration store:[%ld]", p_info->duration);
+  sprintf(buf, "duration=%ld\n", p_info->duration);
+  fputs(buf, p_ctx->all_dat_fp);
+
+  /*Save segment size*/
+  memset(buf, 0, sizeof(buf));
+  sprintf(buf, "size=%zu\n", p_info->size);
+  fputs(buf, p_ctx->all_dat_fp);
+
+  /*Save number of packets*/
+  memset(buf, 0, sizeof(buf));
+  sprintf(buf, "nb_packets=%d\n", p_info->nb_packets);
+  fputs(buf, p_ctx->all_dat_fp);
+
+  fflush(p_ctx->all_dat_fp);
+  fsync(fileno(p_ctx->all_dat_fp));
+  return DVR_SUCCESS;
+}
+
+/* Should consider the case of cut power, todo... */
 int segment_load_info(Segment_Handle_t handle, Segment_StoreInfo_t *p_info)
 {
   Segment_Context_t *p_ctx;
@@ -667,9 +787,13 @@
   DVR_RETURN_IF_FALSE(p1);
   p1 = strstr(buf, "nb_pids=");
   DVR_RETURN_IF_FALSE(p1);
-  p_info->nb_pids = strtoull(p1 + 8, NULL, 10);
+  p_info->nb_pids = strtoul(p1 + 8, NULL, 10);
 
   /*Save pid information*/
+
+  // Tainted data issue originating from fgets seem false positive, so we
+  // just suppress it here.
+  // coverity[tainted_data]
   for (i = 0; i < p_info->nb_pids; i++) {
     p1 = fgets(buf, sizeof(buf), p_ctx->dat_fp);
     DVR_RETURN_IF_FALSE(p1);
@@ -702,7 +826,7 @@
   p1 = strstr(buf, "duration=");
   DVR_RETURN_IF_FALSE(p1);
   p_info->duration = strtoull(p1 + 9, NULL, 10);
-  //DVR_DEBUG(1, "load info p_info->duration:%lld", p_info->duration);
+  //DVR_INFO("load info p_info->duration:%lld", p_info->duration);
 
   /*Save segment size*/
   p1 = fgets(buf, sizeof(buf), p_ctx->dat_fp);
@@ -721,6 +845,107 @@
   return DVR_SUCCESS;
 }
 
+/* Should consider the case of cut power, todo... */
+int segment_load_allInfo(Segment_Handle_t handle, struct list_head *list)
+{
+  Segment_Context_t *p_ctx;
+  uint32_t i;
+  char buf[256];
+  char value[256];
+  char *p1, *p2;
+
+  p_ctx = (Segment_Context_t *)handle;
+  DVR_RETURN_IF_FALSE(p_ctx);
+  DVR_RETURN_IF_FALSE(list);
+  if (p_ctx->all_dat_fp == NULL) {
+    DVR_INFO("all dat file not open\n");
+    return DVR_FAILURE;
+  }
+  //first get
+  p1 = fgets(buf, sizeof(buf), p_ctx->all_dat_fp);
+  DVR_RETURN_IF_FALSE(p1);
+
+  do {
+
+    DVR_RecordSegmentInfo_t *p_info;
+
+    p_info = malloc(sizeof(DVR_RecordSegmentInfo_t));
+    DVR_RETURN_IF_FALSE(p_info);
+    memset(p_info, 0, sizeof(DVR_RecordSegmentInfo_t));
+
+    list_add_tail(p_info, list);
+
+    /*Load segment id*/
+    DVR_RETURN_IF_FALSE(p1);
+    p1 = strstr(buf, "id=");
+    DVR_RETURN_IF_FALSE(p1);
+    p_info->id = strtoull(p1 + 3, NULL, 10);
+
+    /*Save number of pids*/
+    p1 = fgets(buf, sizeof(buf), p_ctx->all_dat_fp);
+    DVR_RETURN_IF_FALSE(p1);
+    p1 = strstr(buf, "nb_pids=");
+    DVR_RETURN_IF_FALSE(p1);
+    p_info->nb_pids = strtoull(p1 + 8, NULL, 10);
+
+    /*Save pid information*/
+    // Tainted data issue originating from fgets seem false positive, so we
+    // just suppress it here.
+    // coverity[tainted_data]
+    for (i = 0; i < p_info->nb_pids; i++) {
+      p1 = fgets(buf, sizeof(buf), p_ctx->all_dat_fp);
+      DVR_RETURN_IF_FALSE(p1);
+      memset(value, 0, sizeof(value));
+      if ((p1 = strstr(buf, "pid="))) {
+        DVR_RETURN_IF_FALSE(p1);
+        p1 += 4;
+        if ((p2 = strstr(buf, ","))) {
+          DVR_RETURN_IF_FALSE(p2);
+          memcpy(value, p1, p2 - p1);
+        }
+        p_info->pids[i].pid = strtoull(value, NULL, 10);
+      }
+
+      memset(value, 0, sizeof(value));
+      if ((p1 = strstr(buf, "type="))) {
+        DVR_RETURN_IF_FALSE(p1);
+        p1 += 5;
+        if ((p2 = strstr(buf, "}"))) {
+          DVR_RETURN_IF_FALSE(p2);
+          memcpy(value, p1, p2 - p1);
+        }
+        p_info->pids[i].type = strtoull(value, NULL, 10);
+      }
+    }
+
+    /*Save segment duration*/
+    p1 = fgets(buf, sizeof(buf), p_ctx->all_dat_fp);
+    DVR_RETURN_IF_FALSE(p1);
+    p1 = strstr(buf, "duration=");
+    DVR_RETURN_IF_FALSE(p1);
+    p_info->duration = strtoull(p1 + 9, NULL, 10);
+    //DVR_INFO("load info p_info->duration:%lld", p_info->duration);
+
+    /*Save segment size*/
+    p1 = fgets(buf, sizeof(buf), p_ctx->all_dat_fp);
+    DVR_RETURN_IF_FALSE(p1);
+    p1 = strstr(buf, "size=");
+    DVR_RETURN_IF_FALSE(p1);
+    p_info->size = strtoull(p1 + 5, NULL, 10);
+
+    /*Save number of packets*/
+    p1 = fgets(buf, sizeof(buf), p_ctx->all_dat_fp);
+    DVR_RETURN_IF_FALSE(p1);
+    p1 = strstr(buf, "nb_packets=");
+    DVR_RETURN_IF_FALSE(p1);
+    p_info->nb_packets = strtoull(p1 + 11, NULL, 10);
+    //if reach end,exit loop
+    p1 = fgets(buf, sizeof(buf), p_ctx->all_dat_fp);
+  } while (p1);
+
+  return DVR_SUCCESS;
+}
+
 int segment_delete(const char *location, uint64_t segment_id)
 {
   char fname[MAX_SEGMENT_PATH_SIZE];
@@ -732,21 +957,21 @@
   memset(fname, 0, sizeof(fname));
   segment_get_fname(fname, location, segment_id, SEGMENT_FILE_TYPE_TS);
   ret = unlink(fname);
-  DVR_DEBUG(1, "%s, [%s] return:%s", __func__, fname, strerror(errno));
+  DVR_ERROR("%s, [%s] return:%s", __func__, fname, strerror(errno));
   DVR_RETURN_IF_FALSE(ret == 0);
 
   /*delete index file*/
   memset(fname, 0, sizeof(fname));
   segment_get_fname(fname, location, segment_id, SEGMENT_FILE_TYPE_INDEX);
   unlink(fname);
-  DVR_DEBUG(1, "%s, [%s] return:%s", __func__, fname, strerror(errno));
+  DVR_ERROR("%s, [%s] return:%s", __func__, fname, strerror(errno));
   DVR_RETURN_IF_FALSE(ret == 0);
 
   /*delete store information file*/
   memset(fname, 0, sizeof(fname));
   segment_get_fname(fname, location, segment_id, SEGMENT_FILE_TYPE_DAT);
   unlink(fname);
-  DVR_DEBUG(1, "%s, [%s] return:%s", __func__, fname, strerror(errno));
+  DVR_ERROR("%s, [%s] return:%s", __func__, fname, strerror(errno));
   DVR_RETURN_IF_FALSE(ret == 0);
 
   return DVR_SUCCESS;
@@ -762,20 +987,22 @@
   memset(going_name, 0, sizeof(going_name));
   segment_get_fname(going_name, p_ctx->location, p_ctx->segment_id, SEGMENT_FILE_TYPE_ONGOING);
   int ret = stat(going_name, &mstat);
-  DVR_DEBUG(1, "segment check ongoing  [%s] ret [%d]", going_name, ret);
+  DVR_INFO("segment check ongoing  [%s] ret [%d]", going_name, ret);
   if (ret != 0) {
     return DVR_FAILURE;
   }
   return DVR_SUCCESS;
 }
+
 loff_t segment_dump_pts(Segment_Handle_t handle)
 {
   Segment_Context_t *p_ctx;
   char buf[256];
   char value[256];
-  uint64_t pts;
-  loff_t offset;
+  uint64_t pts = 0;
+  loff_t offset = 0;
   char *p1, *p2;
+  int ret = 0;
 
   p_ctx = (Segment_Context_t *)handle;
   DVR_RETURN_IF_FALSE(p_ctx);
@@ -783,7 +1010,9 @@
   DVR_RETURN_IF_FALSE(p_ctx->ts_fd != -1);
 
   memset(buf, 0, sizeof(buf));
-  DVR_RETURN_IF_FALSE(fseek(p_ctx->index_fp, 0, SEEK_SET) != -1);
+  ret = fseek(p_ctx->index_fp, 0, SEEK_SET);
+  DVR_RETURN_IF_FALSE(ret != -1);
+
   printf("start gets pts\n");
   while (fgets(buf, sizeof(buf), p_ctx->index_fp) != NULL) {
     printf("buf[%s]\n", buf);
@@ -811,3 +1040,24 @@
 
   return 0;
 }
+
+off_t segment_get_cur_segment_size(Segment_Handle_t handle)
+{
+  Segment_Context_t *p_ctx = (Segment_Context_t *)handle;
+  DVR_RETURN_IF_FALSE(p_ctx);
+  DVR_RETURN_IF_FALSE(p_ctx->ts_fd != -1);
+  struct stat sb;
+  int ret=fstat(p_ctx->ts_fd,&sb);
+  if (ret<0) {
+    return -1;
+  }
+  return sb.st_size;
+}
+
+uint64_t segment_get_cur_segment_id(Segment_Handle_t handle)
+{
+  Segment_Context_t *p_ctx = (Segment_Context_t *)handle;
+  DVR_RETURN_IF_FALSE(p_ctx);
+  return p_ctx->segment_id;
+}
+
diff --git a/test/am_ca_test/Makefile b/test/am_ca_test/Makefile
index a2437fb..6ec1d0a 100644
--- a/test/am_ca_test/Makefile
+++ b/test/am_ca_test/Makefile
@@ -16,11 +16,11 @@
 all : $(OBJS) $(OUTPUT)
 
 $(OBJS) : %.o : %.c
-	$(CC) $(CFLAGS) -c $< -o $@
+    $(CC) $(CFLAGS) -c $< -o $@
 
 $(OUTPUT) : $(OBJS)
-	$(CC) -o $@ $^ $(LDFLAGS)
-	$(STRIP) $(OUTPUT)
+    $(CC) -o $@ $^ $(LDFLAGS)
+    $(STRIP) $(OUTPUT)
 
 clean:
-	@rm -f $(OBJS)
+    @rm -f $(OBJS)
diff --git a/test/am_ca_test/am_ca.c b/test/am_ca_test/am_ca.c
index 1436739..731b664 100644
--- a/test/am_ca_test/am_ca.c
+++ b/test/am_ca_test/am_ca.c
@@ -46,8 +46,8 @@
  * API functions
  ***************************************************************************/
 struct _dsc_dev{
-	int used;
-	int fd;
+    int used;
+    int fd;
 };
 typedef struct _dsc_dev dsc_dev;
 
@@ -56,121 +56,121 @@
 
 int ca_open (int devno)
 {
-	int fd;
-	char buf[32];
-	static int init_flag = 0;
+    int fd;
+    char buf[32];
+    static int init_flag = 0;
 
-	printf("ca_open enter\n");
-	if (!init_flag) {
-		init_flag = 1;
-		memset(&rec_dsc_dev, 0, sizeof(rec_dsc_dev));
-	}
-	if (devno >= MAX_DSC_DEV) {
-		return -1;
-	}
-	if (rec_dsc_dev[devno].used)
-		return 0;
+    printf("ca_open enter\n");
+    if (!init_flag) {
+        init_flag = 1;
+        memset(&rec_dsc_dev, 0, sizeof(rec_dsc_dev));
+    }
+    if (devno >= MAX_DSC_DEV) {
+        return -1;
+    }
+    if (rec_dsc_dev[devno].used)
+        return 0;
 
-	snprintf(buf, sizeof(buf), DEV_NAME"%d", devno);
-	fd = open(buf, O_RDWR);
-	if (fd == -1)
-	{
-		printf("cannot open \"%s\" (%d:%s)", DEV_NAME, errno, strerror(errno));
-		return 0;
-	}
-	rec_dsc_dev[devno].fd = fd;
-	rec_dsc_dev[devno].used = 1;
-	return 0;
+    snprintf(buf, sizeof(buf), DEV_NAME"%d", devno);
+    fd = open(buf, O_RDWR);
+    if (fd == -1)
+    {
+        printf("cannot open \"%s\" (%d:%s)", DEV_NAME, errno, strerror(errno));
+        return 0;
+    }
+    rec_dsc_dev[devno].fd = fd;
+    rec_dsc_dev[devno].used = 1;
+    return 0;
 }
 
 int ca_alloc_chan (int devno, unsigned int pid, int algo, int dsc_type)
 {
-	int ret = 0;
-	int fd = 0;
-	struct ca_sc2_descr_ex desc;
+    int ret = 0;
+    int fd = 0;
+    struct ca_sc2_descr_ex desc;
 
-	printf("ca_alloc_chan dev:%d, pid:0x%0x, algo:%d, dsc_type:%d\n", devno, pid, algo, dsc_type);
-	desc.cmd = CA_ALLOC;
-	desc.params.alloc_params.pid = pid;
-	desc.params.alloc_params.algo = algo;
-	desc.params.alloc_params.dsc_type = dsc_type;
-	desc.params.alloc_params.ca_index = -1;
+    printf("ca_alloc_chan dev:%d, pid:0x%0x, algo:%d, dsc_type:%d\n", devno, pid, algo, dsc_type);
+    desc.cmd = CA_ALLOC;
+    desc.params.alloc_params.pid = pid;
+    desc.params.alloc_params.algo = algo;
+    desc.params.alloc_params.dsc_type = dsc_type;
+    desc.params.alloc_params.ca_index = -1;
 
-	if (devno >= MAX_DSC_DEV || !rec_dsc_dev[devno].used) {
-		return -1;
-	}
-	fd = rec_dsc_dev[devno].fd;
-	ret = ioctl(fd, CA_SC2_SET_DESCR_EX, &desc);
-	if (ret != 0) {
-		printf(" ca_alloc_chan ioctl fail, ret:0x%0x\n", ret);
-		return -1;
-	}
-	printf("ca_alloc_chan, index:%d\n",desc.params.alloc_params.ca_index);
-	return desc.params.alloc_params.ca_index;
+    if (devno >= MAX_DSC_DEV || !rec_dsc_dev[devno].used) {
+        return -1;
+    }
+    fd = rec_dsc_dev[devno].fd;
+    ret = ioctl(fd, CA_SC2_SET_DESCR_EX, &desc);
+    if (ret != 0) {
+        printf(" ca_alloc_chan ioctl fail, ret:0x%0x\n", ret);
+        return -1;
+    }
+    printf("ca_alloc_chan, index:%d\n",desc.params.alloc_params.ca_index);
+    return desc.params.alloc_params.ca_index;
 }
 
 int ca_free_chan (int devno, int index)
 {
-	int ret = 0;
-	int fd = rec_dsc_dev[devno].fd;
-	struct ca_sc2_descr_ex desc;
+    int ret = 0;
+    int fd = rec_dsc_dev[devno].fd;
+    struct ca_sc2_descr_ex desc;
 
-	printf("ca_free_chan:%d, index:%d\n", devno, index);
-	desc.cmd = CA_FREE;
-	desc.params.free_params.ca_index = index;
+    printf("ca_free_chan:%d, index:%d\n", devno, index);
+    desc.cmd = CA_FREE;
+    desc.params.free_params.ca_index = index;
 
-	if (devno >= MAX_DSC_DEV || !rec_dsc_dev[devno].used) {
-		return -1;
-	}
-	fd = rec_dsc_dev[devno].fd;
-	ret = ioctl(fd, CA_SC2_SET_DESCR_EX, &desc);
-	if (ret != 0) {
-		printf(" ca_free_chan ioctl fail\n");
-		return -1;
-	}
-	printf("ca_free_chan, index:%d\n",index);
-	return 0;
+    if (devno >= MAX_DSC_DEV || !rec_dsc_dev[devno].used) {
+        return -1;
+    }
+    fd = rec_dsc_dev[devno].fd;
+    ret = ioctl(fd, CA_SC2_SET_DESCR_EX, &desc);
+    if (ret != 0) {
+        printf(" ca_free_chan ioctl fail\n");
+        return -1;
+    }
+    printf("ca_free_chan, index:%d\n",index);
+    return 0;
 }
 
 
 int ca_set_key (int devno, int index, int parity, int key_index)
 {
-	int ret = 0;
-	int fd = 0;
-	struct ca_sc2_descr_ex desc;
+    int ret = 0;
+    int fd = 0;
+    struct ca_sc2_descr_ex desc;
 
-	printf("ca_set_key dev:%d, index:%d, parity:%d, key_index:%d\n",
-			devno, index, parity, key_index);
-	desc.cmd = CA_KEY;
-	desc.params.key_params.ca_index = index;
-	desc.params.key_params.parity = parity;
-	desc.params.key_params.key_index = key_index;
+    printf("ca_set_key dev:%d, index:%d, parity:%d, key_index:%d\n",
+            devno, index, parity, key_index);
+    desc.cmd = CA_KEY;
+    desc.params.key_params.ca_index = index;
+    desc.params.key_params.parity = parity;
+    desc.params.key_params.key_index = key_index;
 
-	if (devno >= MAX_DSC_DEV || !rec_dsc_dev[devno].used) {
-		return -1;
-	}
-	fd = rec_dsc_dev[devno].fd;
-	ret = ioctl(fd, CA_SC2_SET_DESCR_EX, &desc);
-	if (ret != 0) {
-		printf(" ca_set_key ioctl fail, ret:0x%0x\n", ret);
-		return -1;
-	}
-	printf("ca_set_key, index:%d, parity:%d, key_index:%d\n",index, parity, key_index);
-	return 0;
+    if (devno >= MAX_DSC_DEV || !rec_dsc_dev[devno].used) {
+        return -1;
+    }
+    fd = rec_dsc_dev[devno].fd;
+    ret = ioctl(fd, CA_SC2_SET_DESCR_EX, &desc);
+    if (ret != 0) {
+        printf(" ca_set_key ioctl fail, ret:0x%0x\n", ret);
+        return -1;
+    }
+    printf("ca_set_key, index:%d, parity:%d, key_index:%d\n",index, parity, key_index);
+    return 0;
 }
 
 int ca_close (int devno)
 {
-	int fd = 0;
+    int fd = 0;
 
-	printf("ca_close dev:%d\n", devno);
-	if (devno >= MAX_DSC_DEV || !rec_dsc_dev[devno].used) {
-		return -1;
-	}
-	fd = rec_dsc_dev[devno].fd;
-	close(fd);
-	rec_dsc_dev[devno].fd = 0;
-	rec_dsc_dev[devno].used = 0;
-	return 0;
+    printf("ca_close dev:%d\n", devno);
+    if (devno >= MAX_DSC_DEV || !rec_dsc_dev[devno].used) {
+        return -1;
+    }
+    fd = rec_dsc_dev[devno].fd;
+    close(fd);
+    rec_dsc_dev[devno].fd = 0;
+    rec_dsc_dev[devno].used = 0;
+    return 0;
 }
 
diff --git a/test/am_ca_test/am_ca_test.c b/test/am_ca_test/am_ca_test.c
index cb2c13e..85fafc1 100644
--- a/test/am_ca_test/am_ca_test.c
+++ b/test/am_ca_test/am_ca_test.c
@@ -30,33 +30,33 @@
 
 #define FEND_DEV_NO   (0)
 
-static int s_last_num =-1;
+static int s_last_num = -1;
 
 int freq = 0;
 int layer = -1;
-int src=0;
-int dmx=0;
-int timeout = 60*3;
+int src = 0;
+int dmx = 0;
+int timeout = 60 * 3;
 
-static int bat=0;
-static int nit=0;
-static int user=0;
-static int pat=0;
-static int eit=0;
-static int pall=0;
+static int bat = 0;
+static int nit = 0;
+static int user = 0;
+static int pat = 0;
+static int eit = 0;
+static int pall = 0;
 
 #define USER_MAX 10
-static int u_pid[USER_MAX]={[0 ... USER_MAX-1] = -1};
-static int u_para[USER_MAX]={[0 ... USER_MAX-1] = 0};
-static char *u_ext[USER_MAX]={[0 ... USER_MAX-1] = NULL};
-static char *u_dsc_algo[USER_MAX]={[0 ... USER_MAX-1] = NULL};
-static char *u_odd_iv[USER_MAX]={[0 ... USER_MAX-1] = NULL};
-static char *u_odd_key[USER_MAX]={[0 ... USER_MAX-1] = NULL};
-static char *u_even_iv[USER_MAX]={[0 ... USER_MAX-1] = NULL};
-static char *u_even_key[USER_MAX]={[0 ... USER_MAX-1] = NULL};
-static char *u_00_iv[USER_MAX]={[0 ... USER_MAX-1] = NULL};
-static char *u_00_key[USER_MAX]={[0 ... USER_MAX-1] = NULL};
-static int u_bs[USER_MAX]={[0 ... USER_MAX-1] = 0};
+static int u_pid[USER_MAX] = {[0 ... USER_MAX-1] = -1};
+static int u_para[USER_MAX] = {[0 ... USER_MAX-1] = 0};
+static char *u_ext[USER_MAX] = {[0 ... USER_MAX-1] = NULL};
+static char *u_dsc_algo[USER_MAX] = {[0 ... USER_MAX-1] = NULL};
+static char *u_odd_iv[USER_MAX] = {[0 ... USER_MAX-1] = NULL};
+static char *u_odd_key[USER_MAX] = {[0 ... USER_MAX-1] = NULL};
+static char *u_even_iv[USER_MAX] = {[0 ... USER_MAX-1] = NULL};
+static char *u_even_key[USER_MAX] = {[0 ... USER_MAX-1] = NULL};
+static char *u_00_iv[USER_MAX] = {[0 ... USER_MAX-1] = NULL};
+static char *u_00_key[USER_MAX] = {[0 ... USER_MAX-1] = NULL};
+static int u_bs[USER_MAX] = {[0 ... USER_MAX-1] = 0};
 static int u_para_g;
 static FILE *fp[USER_MAX];
 static FILE *fp_e[USER_MAX];
@@ -71,579 +71,579 @@
 static int key_index[128];
 /*
    u_para format:
-	d1 - 0:sec 1:pes
-	d2 - 1:crc : sec only
-	d3 - 1:print
-	d4 - 1:swfilter
-	d5 - 1:ts_tap :pes only
-	d6 - 1:w2file
+    d1 - 0:sec 1:pes
+    d2 - 1:crc : sec only
+    d3 - 1:print
+    d4 - 1:swfilter
+    d5 - 1:ts_tap :pes only
+    d6 - 1:w2file
 */
-#define UPARA_TYPE      0xf
-#define UPARA_CRC       0xf0
-#define UPARA_PR        0xf00
-#define UPARA_SF        0xf000
-#define UPARA_DMX_TAP   0xf0000
-#define UPARA_FILE      0xf00000
-#define UPARA_PES2ES    0xf000000
-#define UPARA_CA 		0x20000000
-#define UPARA_ES 		0x40000000
-#define UPARA_PCR 		0x80000000
+#define PARA_TYPE      0xf
+#define PARA_CRC       0xf0
+#define PARA_PR        0xf00
+#define PARA_SF        0xf000
+#define PARA_DMX_TAP   0xf0000
+#define PARA_FILE      0xf00000
+#define PARA_PES2ES    0xf000000
+#define PARA_CA         0x20000000
+#define PARA_ES         0x40000000
+#define PARA_PCR         0x80000000
 
-#define get_upara(_i) (u_para[(_i)]? u_para[(_i)] : u_para_g)
+#define get_u_para(_i) (u_para[(_i)]? u_para[(_i)] : u_para_g)
 
 #if 0
 static void pes_cb(AM_PES_Handle_t handle, uint8_t *buf, int size) {
-	int u = (int)(long)AM_PES_GetUserData(handle);
-	printf("pes cb u=%d b=%p, s:%d\n", u, buf, size);
-	int ret = fwrite(buf, 1, size, fp_e[u-1]);
-	if (ret != size)
-		printf("data w lost\n");
+    int u = (int)(long)AM_PES_GetUserData(handle);
+    printf("pes cb u=%d b=%p, s:%d\n", u, buf, size);
+    int ret = fwrite(buf, 1, size, fp_e[u-1]);
+    if (ret != size)
+        printf("data w lost\n");
 
 }
 #endif
 static void dump_bytes(int dev_no, int fid, const uint8_t *data, int len, void *user_data)
 {
-	int u = (int)(long)user_data;
+    int u = (int)(long)user_data;
 
-	if (pall) {
-		int i;
-		printf("data:\n");
-		for(i=0;i<len;i++)
-		{
-			printf("%02x ", data[i]);
-			if(((i+1)%16)==0) printf("\n");
-		}
-		if((i%16)!=0) printf("\n");
-	}
+    if (pall) {
+        int i;
+        printf("data:\n");
+        for (i = 0; i < len; i++)
+        {
+            printf("%02x ", data[i]);
+            if (((i + 1) % 16) == 0) printf("\n");
+        }
+        if ((i % 16) != 0 ) printf("\n");
+    }
 #if 1
-	if (bat&UPARA_PR) {
-		if(data[0]==0x4a) {
-			printf("sec:tabid:0x%02x,bunqid:0x%02x%02x,section num:%4d,lat_section_num:%4d\n",data[0],
-				data[3],data[4],data[6],data[7]);
-		}
+    if (bat & PARA_PR) {
+        if (data[0] == 0x4a) {
+            printf("sec:tabid:0x%02x,bouquet_id:0x%02x%02x,section num:%4d,lat_section_num:%4d\n", data[0],
+                data[3], data[4], data[6], data[7]);
+        }
 
-	}
-	else if (nit&UPARA_PR) {
+    }
+    else if (nit & PARA_PR) {
 
-		if(data[0]==0x40) {
-			printf("section:%8d,max:%8d\n",data[6],data[7]);
-			if((data[6] !=s_last_num+1)&&(s_last_num!=-1))//µÚÒ»¸ö»òÕß²»Á¬Ðø
-			{
-				if(s_last_num ==data[7])//ÉÏÒ»¸öÊÇMAX
-				{
-					if(data[6] != 0)//ÉÏÒ»¸öMAX Õâ¸ö²»ÊÇ 0
-					{
-						printf("##drop packet,tabid:0x%4x,cur:%8d,last:%8d,max:%8d\n",data[0],
-						data[6],s_last_num,data[7]);
-						//stop_section_flag =1;
-					}
-					else
-					{
-					}
-				}
-				else//ÉÏÒ»¸ö²»ÊÇ
-				{
-					printf("##drop packet,tabid:%4x,cur:%8d,last:%8d,max:%8d\n",data[0],
-					data[6],s_last_num,data[7]);
-					//stop_section_flag =1;
-				}
-			}
-			else
-			{
-				//printf("section:%8d,",sectiondata->m_pucData[6]);
-			}
-			s_last_num = data[6];
-		}
-	}
-	else if (pat&UPARA_PR) {
-		if (data[0]==0x0)
-			printf("%02x: %02x %02x %02x %02x %02x %02x %02x %02x\n", data[0], data[1], data[2], data[3], data[4],
-				data[5], data[6], data[7], data[8]);
-	}
-	else {
-		if (!user_data) {
-			printf("%02x %02x %02x %02x %02x %02x %02x %02x %02x\n", data[0], data[1], data[2], data[3], data[4],
-				data[5], data[6], data[7], data[8]);
-			return;
-		}
+        if (data[0] == 0x40) {
+            printf("section:%8d,max:%8d\n", data[6], data[7]);
+            if ((data[6] != s_last_num + 1) && (s_last_num != -1))//µÚÒ»¸ö»òÕß²»Á¬Ðø
+            {
+                if (s_last_num == data[7])//ÉÏÒ»¸öÊÇMAX
+                {
+                    if (data[6] != 0)//ÉÏÒ»¸öMAX Õâ¸ö²»ÊÇ 0
+                    {
+                        printf("##drop packet,tabid:0x%4x,cur:%8d,last:%8d,max:%8d\n", data[0],
+                        data[6], s_last_num, data[7]);
+                        //stop_section_flag =1;
+                    }
+                    else
+                    {
+                    }
+                }
+                else//ÉÏÒ»¸ö²»ÊÇ
+                {
+                    printf("##drop packet,tabid:%4x,cur:%8d,last:%8d,max:%8d\n", data[0],
+                    data[6], s_last_num,data[7]);
+                    //stop_section_flag = 1;
+                }
+            }
+            else
+            {
+                //printf("section:%8d,",sectiondata->m_pucData[6]);
+            }
+            s_last_num = data[6];
+        }
+    }
+    else if (pat & PARA_PR) {
+        if (data[0] == 0x0)
+            printf("%02x: %02x %02x %02x %02x %02x %02x %02x %02x\n", data[0], data[1], data[2], data[3], data[4],
+                data[5], data[6], data[7], data[8]);
+    }
+    else {
+        if (!user_data) {
+            printf("%02x %02x %02x %02x %02x %02x %02x %02x %02x\n", data[0], data[1], data[2], data[3], data[4],
+                data[5], data[6], data[7], data[8]);
+            return;
+        }
 
-		if (get_upara(u-1)&UPARA_PR)
-			printf("[%d:%d %d] %02x %02x %02x %02x %02x %02x %02x %02x %02x\n", u-1, u_pid[u-1], len,
-				data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8]);
-		if (get_upara(u-1)&UPARA_FILE){
-			{
-				int ret = fwrite(data, 1, len, fp[u-1]);
-				if (ret != len)
-					printf("data w lost\n");
-			}
+        if (get_u_para(u - 1) & PARA_PR)
+            printf("[%d:%d %d] %02x %02x %02x %02x %02x %02x %02x %02x %02x\n", u-1, u_pid[u-1], len,
+                data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8]);
+        if (get_u_para(u - 1) & PARA_FILE) {
+            {
+                int ret = fwrite(data, 1, len, fp[u - 1]);
+                if (ret != len)
+                    printf("data w lost\n");
+            }
 #if 0
-			if (get_upara(u-1)&UPARA_PES2ES) {
-				if (!h_pes[u-1]) {
-					AM_PES_Para_t para = {.packet = pes_cb, .user_data = (void*)(long)u, .payload_only = AM_TRUE,};
-					AM_PES_Create(&h_pes[u-1], &para);
-				}
-				AM_PES_Decode(h_pes[u-1], data, len);
-			}
+            if (get_u_para(u - 1) & PARA_PES2ES) {
+                if (!h_pes[u - 1]) {
+                    AM_PES_Para_t para = {.packet = pes_cb, .user_data = (void*)(long)u, .payload_only = AM_TRUE,};
+                    AM_PES_Create(&h_pes[u - 1], &para);
+                }
+                AM_PES_Decode(h_pes[u - 1], data, len);
+            }
 #endif
-		}
-	}
+        }
+    }
 #endif
 }
 static void get_key_from_para(char *para_org, int para_len, char *key, int *len)
 {
-	int i = 0;
-	int dst = 0;
-	char hi = 0;
-	char lo = 0;
+    int i = 0;
+    int dst = 0;
+    char hi = 0;
+    char lo = 0;
 
-	printf("get key len:%d, key:%s\n", para_len, para_org);
-	if (para_len <= 2)
-		return ;
-	para_len -= 2;
+    printf("get key len:%d, key:%s\n", para_len, para_org);
+    if (para_len <= 2)
+        return ;
+    para_len -= 2;
 
-	dst = 2;
+    dst = 2;
 
-	printf("key:");
-	while (para_len >= 2) {
-		hi = 0;
-		if (para_org[dst] >= 0x30 && para_org[dst] <= 0x39)	{
-			hi = para_org[dst] - 0x30;
-		} else if (para_org[dst] >= 0x41 && para_org[dst] <= 0x46) {
-			hi = para_org[dst] - 0x37;
-		} else if (para_org[dst] >= 0x61 && para_org[dst] <= 0x66) {
-			hi = para_org[dst] - 0x57;
-		}
-		lo = 0;
-		if (para_org[dst+1] >= 0x30 && para_org[dst+1] <= 0x39)	{
-			lo = para_org[dst+1] - 0x30;
-		} else if (para_org[dst+1] >= 0x41 && para_org[dst+1] <= 0x46) {
-			lo = para_org[dst+1] - 0x37;
-		} else if (para_org[dst+1] >= 0x61 && para_org[dst+1] <= 0x66) {
-			lo = para_org[dst+1] - 0x57;
-		}
-		key[i] = (hi << 4) | lo;
-		printf("0x%0x ", key[i]);
-		i++;
-		dst += 2;
-		para_len -= 2;
-	}
-	printf("\n");
-	*len = i;
+    printf("key:");
+    while (para_len >= 2) {
+        hi = 0;
+        if (para_org[dst] >= 0x30 && para_org[dst] <= 0x39)    {
+            hi = para_org[dst] - 0x30;
+        } else if (para_org[dst] >= 0x41 && para_org[dst] <= 0x46) {
+            hi = para_org[dst] - 0x37;
+        } else if (para_org[dst] >= 0x61 && para_org[dst] <= 0x66) {
+            hi = para_org[dst] - 0x57;
+        }
+        lo = 0;
+        if (para_org[dst+1] >= 0x30 && para_org[dst+1] <= 0x39)    {
+            lo = para_org[dst+1] - 0x30;
+        } else if (para_org[dst+1] >= 0x41 && para_org[dst+1] <= 0x46) {
+            lo = para_org[dst+1] - 0x37;
+        } else if (para_org[dst+1] >= 0x61 && para_org[dst+1] <= 0x66) {
+            lo = para_org[dst+1] - 0x57;
+        }
+        key[i] = (hi << 4) | lo;
+        printf("0x%0x ", key[i]);
+        i++;
+        dst += 2;
+        para_len -= 2;
+    }
+    printf("\n");
+    *len = i;
 }
 
 static int get_section(int dmx, int timeout)
 {
-	int fid_user[USER_MAX];
-	int ca_index[USER_MAX];
-	int i;
-	int pcr_flag = 0;
+    int fid_user[USER_MAX];
+    int ca_index[USER_MAX];
+    int i;
+    int pcr_flag = 0;
 
-	struct dmx_sct_filter_params param;
-	struct dmx_pes_filter_params pparam;
+    struct dmx_sct_filter_params param;
+    struct dmx_pes_filter_params pparam;
 
-	memset(&ca_index, -1, sizeof(ca_index));
+    memset(&ca_index, -1, sizeof(ca_index));
 
-	for(i=0; i<USER_MAX; i++) {
-		if(u_pid[i]!=-1) {
-			printf("set %d\n", __LINE__);
-			AM_TRY(AM_DMX_AllocateFilter(dmx, &fid_user[i]));
-			printf("set %d\n", __LINE__);
+    for (i = 0; i < USER_MAX; i++) {
+        if (u_pid[i] != -1) {
+            printf("set %d\n", __LINE__);
+            AM_TRY(AM_DMX_AllocateFilter(dmx, &fid_user[i]));
+            printf("set %d\n", __LINE__);
 
-			AM_TRY(AM_DMX_SetCallback(dmx, fid_user[i], dump_bytes, (void*)(long)(i+1)));
-			printf("set %d\n", __LINE__);
+            AM_TRY(AM_DMX_SetCallback(dmx, fid_user[i], dump_bytes, (void*)(long)(i + 1)));
+            printf("set %d\n", __LINE__);
 
-			if(u_bs[i]) {
-				AM_TRY(AM_DMX_SetBufferSize(dmx, fid_user[i], u_bs[i]));
-				printf("buffersize => %d\n", u_bs[i]);
-			}
-			printf("set %d\n", __LINE__);
+            if (u_bs[i]) {
+                AM_TRY(AM_DMX_SetBufferSize(dmx, fid_user[i], u_bs[i]));
+                printf("buffersize => %d\n", u_bs[i]);
+            }
+            printf("set %d\n", __LINE__);
 
-			if (get_upara(i) & UPARA_CA) {
-					int dsc_algo = 0;
-					int dsc_type = 0;
-					int parity = 0;
-					int key_userid = 0;
-					int key_algo = 0;
-					char key[32];
-					char key_len = 0;
+            if (get_u_para(i) & PARA_CA) {
+                    int dsc_algo = 0;
+                    int dsc_type = 0;
+                    int parity = 0;
+                    int key_userid = 0;
+                    int key_algo = 0;
+                    char key[32];
+                    char key_len = 0;
 
-					ca_open(dmx);
-					key_fd = key_open();
-					if(u_dsc_algo[i]) {
-						sscanf(u_dsc_algo[i], "%x:%x", &dsc_algo, &dsc_type);
-					}
-					if (dsc_type == CA_DSC_COMMON_TYPE)
-						key_userid = DSC_NETWORK;
-					else if (dsc_type == CA_DSC_TSD_TYPE)
-						key_userid = DSC_LOC_DEC;
-					else if (dsc_type == CA_DSC_TSE_TYPE)
-						key_userid = DSC_LOC_ENC;
-					else {
-						printf("dsc_type:%d invalid\n", dsc_type);
-						key_userid = DSC_NETWORK;
-					}
+                    ca_open(dmx);
+                    key_fd = key_open();
+                    if (u_dsc_algo[i]) {
+                        sscanf(u_dsc_algo[i], "%x:%x", &dsc_algo, &dsc_type);
+                    }
+                    if (dsc_type == CA_DSC_COMMON_TYPE)
+                        key_userid = DSC_NETWORK;
+                    else if (dsc_type == CA_DSC_TSD_TYPE)
+                        key_userid = DSC_LOC_DEC;
+                    else if (dsc_type == CA_DSC_TSE_TYPE)
+                        key_userid = DSC_LOC_ENC;
+                    else {
+                        printf("dsc_type:%d invalid\n", dsc_type);
+                        key_userid = DSC_NETWORK;
+                    }
 
-					switch (dsc_algo){
-						case CA_ALGO_AES_ECB_CLR_END:
-						case CA_ALGO_AES_ECB_CLR_FRONT:
-						case CA_ALGO_AES_CBC_CLR_END:
-						case CA_ALGO_AES_CBC_IDSA:
-						case CA_ALGO_CPCM_LSA_MDI_CBC:
-						case CA_ALGO_CPCM_LSA_MDD_CBC:
-							key_algo = KEY_ALGO_AES;
-							break;
-						case CA_ALGO_TDES_ECB_CLR_END:
-							key_algo = KEY_ALGO_TDES;
-							break;
-						case CA_ALGO_DES_SCTE41:
-						case CA_ALGO_DES_SCTE52:
-							key_algo = KEY_ALGO_DES;
-							break;
-						case CA_ALGO_CSA2:
-							key_algo = KEY_ALGO_CSA2;
-							break;
-						case CA_ALGO_CSA3 :
-							key_algo = KEY_ALGO_CSA3;
-							break;
-						case CA_ALGO_ASA:
-							key_algo = KEY_ALGO_ND;
-							break;
-						case CA_ALGO_ASA_LIGHT:
-							key_algo = KEY_ALGO_NDL;
-							break;
-						case CA_ALGO_S17_ECB_CLR_END:
-						case CA_ALGO_S17_ECB_CTS:
-							key_algo = KEY_ALGO_S17;
-							break;
-						default:
-							printf("dsc algo:%d error\n", dsc_algo);
-					}
-					ca_index[i] = ca_alloc_chan(dmx, u_pid[i], dsc_algo, dsc_type);
+                    switch (dsc_algo) {
+                        case CA_ALGO_AES_ECB_CLR_END:
+                        case CA_ALGO_AES_ECB_CLR_FRONT:
+                        case CA_ALGO_AES_CBC_CLR_END:
+                        case CA_ALGO_AES_CBC_IDSA:
+                        case CA_ALGO_CPCM_LSA_MDI_CBC:
+                        case CA_ALGO_CPCM_LSA_MDD_CBC:
+                            key_algo = KEY_ALGO_AES;
+                            break;
+                        case CA_ALGO_TDES_ECB_CLR_END:
+                            key_algo = KEY_ALGO_TDES;
+                            break;
+                        case CA_ALGO_DES_SCTE41:
+                        case CA_ALGO_DES_SCTE52:
+                            key_algo = KEY_ALGO_DES;
+                            break;
+                        case CA_ALGO_CSA2:
+                            key_algo = KEY_ALGO_CSA2;
+                            break;
+                        case CA_ALGO_CSA3 :
+                            key_algo = KEY_ALGO_CSA3;
+                            break;
+                        case CA_ALGO_ASA:
+                            key_algo = KEY_ALGO_ND;
+                            break;
+                        case CA_ALGO_ASA_LIGHT:
+                            key_algo = KEY_ALGO_NDL;
+                            break;
+                        case CA_ALGO_S17_ECB_CLR_END:
+                        case CA_ALGO_S17_ECB_CTS:
+                            key_algo = KEY_ALGO_S17;
+                            break;
+                        default:
+                            printf("dsc algo:%d error\n", dsc_algo);
+                    }
+                    ca_index[i] = ca_alloc_chan(dmx, u_pid[i], dsc_algo, dsc_type);
 
-					if (u_odd_key[i]) {
-						memset(key, 0, sizeof(key));
-						get_key_from_para(u_odd_key[i],strlen(u_odd_key[i]), key, &key_len);
-						key_index[s_index] = key_alloc(key_fd, 0);
-						key_config(key_fd, key_index[s_index], key_userid, key_algo, 0);
-						key_set(key_fd, key_index[s_index], key, key_len);
-						ca_set_key(dmx, ca_index[i], CA_KEY_ODD_TYPE, key_index[s_index]);
-						s_index++;
-					}
-					if (u_even_key[i]) {
-						memset(key, 0, sizeof(key));
-						get_key_from_para(u_even_key[i],strlen(u_even_key[i]), key, &key_len);
-						key_index[s_index] = key_alloc(key_fd, 0);
-						key_config(key_fd, key_index[s_index], key_userid, key_algo, 0);
-						key_set(key_fd, key_index[s_index],key, key_len);
-						ca_set_key(dmx, ca_index[i], CA_KEY_EVEN_TYPE, key_index[s_index]);
-						s_index++;
-					}
-					if (u_00_key[i]) {
-						memset(key, 0, sizeof(key));
-						get_key_from_para(u_00_key[i],strlen(u_00_key[i]), key, &key_len);
-						key_index[s_index] = key_alloc(key_fd, 0);
-						key_config(key_fd, key_index[s_index], key_userid, key_algo, 0);
-						key_set(key_fd, key_index[s_index], key, key_len);
-						ca_set_key(dmx, ca_index[i], CA_KEY_00_TYPE, key_index[s_index]);
-						s_index++;
-					}
-					if (u_odd_iv[i]) {
-						memset(key, 0, sizeof(key));
-						get_key_from_para(u_odd_iv[i],strlen(u_odd_iv[i]), key, &key_len);
-						key_index[s_index] =  key_alloc(key_fd, 1);
-						key_config(key_fd, key_index[s_index], key_userid, key_algo, 0);
-						key_set(key_fd, key_index[s_index], key, key_len);
-						ca_set_key(dmx, ca_index[i], CA_KEY_ODD_IV_TYPE, key_index[s_index]);
-						s_index++;
-					}
-					if (u_even_iv[i]) {
-						memset(key, 0, sizeof(key));
-						get_key_from_para(u_even_iv[i],strlen(u_even_iv[i]), key, &key_len);
-						key_index[s_index] = key_alloc(key_fd, 1);
-						key_config(key_fd, key_index[s_index], key_userid, key_algo, 0);
-						key_set(key_fd, key_index[s_index], key, key_len);
-						ca_set_key(dmx, ca_index[i], CA_KEY_EVEN_IV_TYPE, key_index[s_index]);
-						s_index++;
-					}
-					if (u_00_iv[i]) {
-						memset(key, 0, sizeof(key));
-						get_key_from_para(u_00_iv[i],strlen(u_00_iv[i]), key, &key_len);
-						key_index[s_index] =  key_alloc(key_fd, 1);
-						key_config(key_fd, key_index[s_index], key_userid, key_algo, 0);
-						key_set(key_fd, key_index[s_index], key, key_len);
-						ca_set_key(dmx, ca_index[i], CA_KEY_00_IV_TYPE, key_index[s_index]);
-						s_index++;
-					}
-			}
+                    if (u_odd_key[i]) {
+                        memset(key, 0, sizeof(key));
+                        get_key_from_para(u_odd_key[i], strlen(u_odd_key[i]), key, &key_len);
+                        key_index[s_index] = key_alloc(key_fd, 0);
+                        key_config(key_fd, key_index[s_index], key_userid, key_algo, 0);
+                        key_set(key_fd, key_index[s_index], key, key_len);
+                        ca_set_key(dmx, ca_index[i], CA_KEY_ODD_TYPE, key_index[s_index]);
+                        s_index++;
+                    }
+                    if (u_even_key[i]) {
+                        memset(key, 0, sizeof(key));
+                        get_key_from_para(u_even_key[i], strlen(u_even_key[i]), key, &key_len);
+                        key_index[s_index] = key_alloc(key_fd, 0);
+                        key_config(key_fd, key_index[s_index], key_userid, key_algo, 0);
+                        key_set(key_fd, key_index[s_index],key, key_len);
+                        ca_set_key(dmx, ca_index[i], CA_KEY_EVEN_TYPE, key_index[s_index]);
+                        s_index++;
+                    }
+                    if (u_00_key[i]) {
+                        memset(key, 0, sizeof(key));
+                        get_key_from_para(u_00_key[i], strlen(u_00_key[i]), key, &key_len);
+                        key_index[s_index] = key_alloc(key_fd, 0);
+                        key_config(key_fd, key_index[s_index], key_userid, key_algo, 0);
+                        key_set(key_fd, key_index[s_index], key, key_len);
+                        ca_set_key(dmx, ca_index[i], CA_KEY_00_TYPE, key_index[s_index]);
+                        s_index++;
+                    }
+                    if (u_odd_iv[i]) {
+                        memset(key, 0, sizeof(key));
+                        get_key_from_para(u_odd_iv[i], strlen(u_odd_iv[i]), key, &key_len);
+                        key_index[s_index] =  key_alloc(key_fd, 1);
+                        key_config(key_fd, key_index[s_index], key_userid, key_algo, 0);
+                        key_set(key_fd, key_index[s_index], key, key_len);
+                        ca_set_key(dmx, ca_index[i], CA_KEY_ODD_IV_TYPE, key_index[s_index]);
+                        s_index++;
+                    }
+                    if (u_even_iv[i]) {
+                        memset(key, 0, sizeof(key));
+                        get_key_from_para(u_even_iv[i], strlen(u_even_iv[i]), key, &key_len);
+                        key_index[s_index] = key_alloc(key_fd, 1);
+                        key_config(key_fd, key_index[s_index], key_userid, key_algo, 0);
+                        key_set(key_fd, key_index[s_index], key, key_len);
+                        ca_set_key(dmx, ca_index[i], CA_KEY_EVEN_IV_TYPE, key_index[s_index]);
+                        s_index++;
+                    }
+                    if (u_00_iv[i]) {
+                        memset(key, 0, sizeof(key));
+                        get_key_from_para(u_00_iv[i], strlen(u_00_iv[i]), key, &key_len);
+                        key_index[s_index] =  key_alloc(key_fd, 1);
+                        key_config(key_fd, key_index[s_index], key_userid, key_algo, 0);
+                        key_set(key_fd, key_index[s_index], key, key_len);
+                        ca_set_key(dmx, ca_index[i], CA_KEY_00_IV_TYPE, key_index[s_index]);
+                        s_index++;
+                    }
+            }
 
-			if(get_upara(i)&UPARA_TYPE) {/*pes*/
-				memset(&pparam, 0, sizeof(pparam));
-				pparam.pid = u_pid[i];
-				if (get_upara(i) & UPARA_PCR) {
-					pparam.pes_type = DMX_PES_PCR0;
-					printf("set %d\n", __LINE__);
-					pcr_flag = 1;
-				}
-				else
-					pparam.pes_type = DMX_PES_OTHER;
+            if (get_u_para(i) & PARA_TYPE) {/*pes*/
+                memset(&pparam, 0, sizeof(pparam));
+                pparam.pid = u_pid[i];
+                if (get_u_para(i) & PARA_PCR) {
+                    pparam.pes_type = DMX_PES_PCR0;
+                    printf("set %d\n", __LINE__);
+                    pcr_flag = 1;
+                }
+                else
+                    pparam.pes_type = DMX_PES_OTHER;
 
-				pparam.input = DMX_IN_FRONTEND;
-				pparam.output = DMX_OUT_TAP;
-				if(get_upara(i)&UPARA_DMX_TAP)
-					pparam.output = DMX_OUT_TSDEMUX_TAP;
-				if(get_upara(i)&UPARA_SF)
-					pparam.flags |= 0x100;
-				if (get_upara(i) & UPARA_ES) {
-					pparam.flags |= DMX_ES_OUTPUT;
-					printf("set es flag\n");
-				}
-				AM_TRY(AM_DMX_SetPesFilter(dmx, fid_user[i], &pparam));
-			} else {/*sct*/
-				int v[16] = {[0 ... 15] = 0};
-				int m[16] = {[0 ... 15] = 0};
-				int ii;
-				memset(&param, 0, sizeof(param));
-				param.pid = u_pid[i];
-				if(u_ext[i]) {
-				sscanf(u_ext[i], "%x:%x,%x:%x,%x:%x,%x:%x"
-					",%x:%x,%x:%x,%x:%x,%x:%x"
-					",%x:%x,%x:%x,%x:%x,%x:%x"
-					",%x:%x,%x:%x,%x:%x,%x:%x",
-					&v[0], &m[0], &v[1], &m[1],
-					&v[2], &m[2], &v[3], &m[3],
-					&v[4], &m[4], &v[5], &m[5],
-					&v[6], &m[6], &v[7], &m[7],
-					&v[8], &m[8], &v[9], &m[9],
-					&v[10], &m[10], &v[11], &m[11],
-					&v[12], &m[12], &v[13], &m[13],
-					&v[14], &m[14], &v[15], &m[15]);
-				for(ii=0; ii<16; ii++) {
-					if(m[ii]) {
-						param.filter.filter[ii] = v[ii];
-						param.filter.mask[ii] = m[ii];
-						printf("ext%d: [%d]%x:%x\n", i, ii, v[ii], m[ii]);
-					}
-				}
-				}
-				if(get_upara(i)&UPARA_CRC)
-					param.flags = DMX_CHECK_CRC;
-				if(get_upara(i)&UPARA_SF)
-					param.flags |= 0x100;
-				AM_TRY(AM_DMX_SetSecFilter(dmx, fid_user[i], &param));
-			}
+                pparam.input = DMX_IN_FRONTEND;
+                pparam.output = DMX_OUT_TAP;
+                if (get_u_para(i) & PARA_DMX_TAP)
+                    pparam.output = DMX_OUT_TSDEMUX_TAP;
+                if (get_u_para(i) & PARA_SF)
+                    pparam.flags |= 0x100;
+                if (get_u_para(i) & PARA_ES) {
+                    pparam.flags |= DMX_ES_OUTPUT;
+                    printf("set es flag\n");
+                }
+                AM_TRY(AM_DMX_SetPesFilter(dmx, fid_user[i], &pparam));
+            } else {/*sct*/
+                int v[16] = {[0 ... 15] = 0};
+                int m[16] = {[0 ... 15] = 0};
+                int ii;
+                memset(&param, 0, sizeof(param));
+                param.pid = u_pid[i];
+                if (u_ext[i]) {
+                sscanf(u_ext[i], "%x:%x,%x:%x,%x:%x,%x:%x"
+                    ",%x:%x,%x:%x,%x:%x,%x:%x"
+                    ",%x:%x,%x:%x,%x:%x,%x:%x"
+                    ",%x:%x,%x:%x,%x:%x,%x:%x",
+                    &v[0], &m[0], &v[1], &m[1],
+                    &v[2], &m[2], &v[3], &m[3],
+                    &v[4], &m[4], &v[5], &m[5],
+                    &v[6], &m[6], &v[7], &m[7],
+                    &v[8], &m[8], &v[9], &m[9],
+                    &v[10], &m[10], &v[11], &m[11],
+                    &v[12], &m[12], &v[13], &m[13],
+                    &v[14], &m[14], &v[15], &m[15]);
+                for (ii = 0; ii < 16; ii++) {
+                    if (m[ii]) {
+                        param.filter.filter[ii] = v[ii];
+                        param.filter.mask[ii] = m[ii];
+                        printf("ext%d: [%d]%x:%x\n", i, ii, v[ii], m[ii]);
+                    }
+                }
+                }
+                if (get_u_para(i) & PARA_CRC)
+                    param.flags = DMX_CHECK_CRC;
+                if (get_u_para(i) & PARA_SF)
+                    param.flags |= 0x100;
+                AM_TRY(AM_DMX_SetSecFilter(dmx, fid_user[i], &param));
+            }
 
-			if(get_upara(i)&UPARA_FILE) {
-				char name[32];
-				sprintf(name, "%s/u_%d.dump", u_path_g, i);
-				fp[i] = fopen(name, "wb");
-				if (fp[i])
-					printf("file open:[%s]\n", name);
-				sprintf(name, "%s/u_%d.es.dump", u_path_g, i);
-				fp_e[i] = fopen(name, "wb");
-				if (fp_e[i])
-					printf("file open:[%s]\n", name);
-			}
+            if (get_u_para(i) & PARA_FILE) {
+                char name[32];
+                sprintf(name, "%s/u_%d.dump", u_path_g, i);
+                fp[i] = fopen(name, "wb");
+                if (fp[i])
+                    printf("file open:[%s]\n", name);
+                sprintf(name, "%s/u_%d.es.dump", u_path_g, i);
+                fp_e[i] = fopen(name, "wb");
+                if (fp_e[i])
+                    printf("file open:[%s]\n", name);
+            }
 
-			AM_TRY(AM_DMX_StartFilter(dmx, fid_user[i]));
-		}
-	}
+            AM_TRY(AM_DMX_StartFilter(dmx, fid_user[i]));
+        }
+    }
 
-	printf("TS SRC = %d\n", src);
-	if (src == 1 && u_input_g) {
-		printf("inject file :%s\n",u_input_g_file);
-		inject_file(dmx, u_input_g_file);
-	}
-//	sleep(1);
-	if (pcr_flag == 1) {
-		printf("get stc:\n");
-		AM_DMX_GetSTC(dmx, fid_user[0]);
-	}
-	sleep(timeout);
+    printf("TS SRC = %d\n", src);
+    if (src == 1 && u_input_g) {
+        printf("inject file :%s\n",u_input_g_file);
+        inject_file(dmx, u_input_g_file);
+    }
+//    sleep(1);
+    if (pcr_flag == 1) {
+        printf("get stc:\n");
+        AM_DMX_GetSTC(dmx, fid_user[0]);
+    }
+    sleep(timeout);
 
-	for (i = 0; i < USER_MAX; i++) {
-		if (ca_index[i] != -1)
-			ca_free_chan(dmx, ca_index[i]);
-	}
+    for (i = 0; i < USER_MAX; i++) {
+        if (ca_index[i] != -1)
+            ca_free_chan(dmx, ca_index[i]);
+    }
 
-	for (i=0; i < s_index; i++) {
-		if (key_index[i] != -1)
-			key_free(key_fd, key_index[i]);
-	}
+    for (i=0; i < s_index; i++) {
+        if (key_index[i] != -1)
+            key_free(key_fd, key_index[i]);
+    }
 
-	for(i=0; i<USER_MAX; i++) {
-		if(u_pid[i]!=-1) {
-			AM_TRY(AM_DMX_StopFilter(dmx, fid_user[i]));
-			AM_TRY(AM_DMX_FreeFilter(dmx, fid_user[i]));
-			if((get_upara(i)&UPARA_FILE) && fp[i])
-				fclose(fp[i]);
-			if (get_upara(i) & UPARA_CA)
-				ca_free_chan(dmx, ca_index[i]);
-		}
-	}
-	ca_close(dmx);
+    for (i = 0; i < USER_MAX; i++) {
+        if (u_pid[i] != -1) {
+            AM_TRY(AM_DMX_StopFilter(dmx, fid_user[i]));
+            AM_TRY(AM_DMX_FreeFilter(dmx, fid_user[i]));
+            if ((get_u_para(i) & PARA_FILE) && fp[i])
+                fclose(fp[i]);
+            if (get_u_para(i) & PARA_CA)
+                ca_free_chan(dmx, ca_index[i]);
+        }
+    }
+    ca_close(dmx);
 
-	return 0;
+    return 0;
 }
 
 #if 0
 static int setlayer(int layer/*1/2/4/7*/)
 {
-	AM_ErrorCode_t ret;
+    AM_ErrorCode_t ret;
 
-	struct dtv_property p = {.cmd=DTV_ISDBT_LAYER_ENABLED, .u.data = layer};
-	struct dtv_properties props = {.num=1, .props=&p};
-	printf("AM FEND SetProp layer:%d\n", props.props[0].u.data);
-	ret = AM_FEND_SetProp(FEND_DEV_NO, &props);
-	return 0;
+    struct dtv_property p = {.cmd = DTV_ISDBT_LAYER_ENABLED, .u.data = layer};
+    struct dtv_properties props = {.num = 1, .props = &p};
+    printf("AM FEND SetProp layer:%d\n", props.props[0].u.data);
+    ret = AM_FEND_SetProp(FEND_DEV_NO, &props);
+    return 0;
 }
 #endif
 
 int get_para(char *argv)
 {
-	#define CASE(name, len, type, var) \
-		if(!strncmp(argv, name"=", (len)+1)) { \
-			sscanf(&argv[(len)+1], type, &var); \
-			printf("param["name"] => "type"\n", var); \
-		}
-	#define CASESTR(name, len, type, var) \
-		if(!strncmp(argv, name"=", (len)+1)) { \
-			var = &argv[(len)+1]; \
-			printf("param["name"] => "type"\n", var); \
-		}
+    #define CASE(name, len, type, var) \
+        if (!strncmp(argv, name"=", (len) + 1)) { \
+            sscanf(&argv[(len)+1], type, &var); \
+            printf("param["name"] => "type"\n", var); \
+        }
+    #define CASESTR(name, len, type, var) \
+        if (!strncmp(argv, name"=", (len) + 1)) { \
+            var = &argv[(len) + 1]; \
+            printf("param["name"] => "type"\n", var); \
+        }
 
-	CASE("freq",      4, "%i", freq)
-	else CASE("src",  3, "%i", src)
-	else CASE("dmx",  3, "%i", dmx)
-	else CASE("pat",  3, "%x", pat)
-	else CASE("eit",  3, "%x", eit)
-	else CASE("layer",5, "%i", layer)
-	else CASE("bat",  3, "%x", bat)
-	else CASE("nit",  3, "%x", nit)
-	else CASE("timeout", 7, "%i", timeout)
-	else CASE("pall", 4, "%i", pall)
-	else CASE("pid0", 4, "%i", u_pid[0])
-	else CASE("pid1", 4, "%i", u_pid[1])
-	else CASE("pid2", 4, "%i", u_pid[2])
-	else CASE("pid3", 4, "%i", u_pid[3])
-	else CASE("pid4", 4, "%i", u_pid[4])
-	else CASE("para0", 5, "%x", u_para[0])
-	else CASE("para1", 5, "%x", u_para[1])
-	else CASE("para2", 5, "%x", u_para[2])
-	else CASE("para3", 5, "%x", u_para[3])
-	else CASE("para4", 5, "%x", u_para[4])
-	else CASESTR("ext0", 4, "%s", u_ext[0])
-	else CASESTR("ext1", 4, "%s", u_ext[1])
-	else CASESTR("ext2", 4, "%s", u_ext[2])
-	else CASESTR("ext3", 4, "%s", u_ext[3])
-	else CASESTR("ext4", 4, "%s", u_ext[4])
-	else CASESTR("da0", 3, "%s", u_dsc_algo[0])
-	else CASESTR("da1", 3, "%s", u_dsc_algo[1])
-	else CASESTR("da2", 3, "%s", u_dsc_algo[2])
-	else CASESTR("da3", 3, "%s", u_dsc_algo[3])
-	else CASESTR("odd_iv0", 7, "%s", u_odd_iv[0])
-	else CASESTR("odd_iv1", 7, "%s", u_odd_iv[1])
-	else CASESTR("odd_iv2", 7, "%s", u_odd_iv[2])
-	else CASESTR("odd_iv3", 7, "%s", u_odd_iv[3])
-	else CASESTR("odd_key0", 8, "%s", u_odd_key[0])
-	else CASESTR("odd_key1", 8, "%s", u_odd_key[1])
-	else CASESTR("odd_key2", 8, "%s", u_odd_key[2])
-	else CASESTR("odd_key3", 8, "%s", u_odd_key[3])
-	else CASESTR("even_iv0", 8, "%s", u_even_iv[0])
-	else CASESTR("even_iv1", 8, "%s", u_even_iv[1])
-	else CASESTR("even_iv2", 8, "%s", u_even_iv[2])
-	else CASESTR("even_iv3", 8, "%s", u_even_iv[3])
-	else CASESTR("even_key0", 9, "%s", u_even_key[0])
-	else CASESTR("even_key1", 9, "%s", u_even_key[1])
-	else CASESTR("even_key2", 9, "%s", u_even_key[2])
-	else CASESTR("even_key3", 9, "%s", u_even_key[3])
-	else CASESTR("00_iv0", 6, "%s", u_00_iv[0])
-	else CASESTR("00_iv1", 6, "%s", u_00_iv[1])
-	else CASESTR("00_iv2", 6, "%s", u_00_iv[2])
-	else CASESTR("00_iv3", 6, "%s", u_00_iv[3])
-	else CASESTR("00_key0", 7, "%s", u_00_key[0])
-	else CASESTR("00_key1", 7, "%s", u_00_key[1])
-	else CASESTR("00_key2", 7, "%s", u_00_key[2])
-	else CASESTR("00_key3", 7, "%s", u_00_key[3])
-	else CASE("bs0", 3, "%i", u_bs[0])
-	else CASE("bs1", 3, "%i", u_bs[1])
-	else CASE("bs2", 3, "%i", u_bs[2])
-	else CASE("bs3", 3, "%i", u_bs[3])
-	else CASE("bs4", 3, "%i", u_bs[4])
-	else CASE("para", 4, "%x", u_para_g)
-	else CASESTR("path", 4, "%s", u_path_g)
-	else CASESTR("input", 4, "%s", u_input_g)
+    CASE("freq",      4, "%i", freq)
+    else CASE("src",  3, "%i", src)
+    else CASE("dmx",  3, "%i", dmx)
+    else CASE("pat",  3, "%x", pat)
+    else CASE("eit",  3, "%x", eit)
+    else CASE("layer",5, "%i", layer)
+    else CASE("bat",  3, "%x", bat)
+    else CASE("nit",  3, "%x", nit)
+    else CASE("timeout", 7, "%i", timeout)
+    else CASE("pall", 4, "%i", pall)
+    else CASE("pid0", 4, "%i", u_pid[0])
+    else CASE("pid1", 4, "%i", u_pid[1])
+    else CASE("pid2", 4, "%i", u_pid[2])
+    else CASE("pid3", 4, "%i", u_pid[3])
+    else CASE("pid4", 4, "%i", u_pid[4])
+    else CASE("para0", 5, "%x", u_para[0])
+    else CASE("para1", 5, "%x", u_para[1])
+    else CASE("para2", 5, "%x", u_para[2])
+    else CASE("para3", 5, "%x", u_para[3])
+    else CASE("para4", 5, "%x", u_para[4])
+    else CASESTR("ext0", 4, "%s", u_ext[0])
+    else CASESTR("ext1", 4, "%s", u_ext[1])
+    else CASESTR("ext2", 4, "%s", u_ext[2])
+    else CASESTR("ext3", 4, "%s", u_ext[3])
+    else CASESTR("ext4", 4, "%s", u_ext[4])
+    else CASESTR("da0", 3, "%s", u_dsc_algo[0])
+    else CASESTR("da1", 3, "%s", u_dsc_algo[1])
+    else CASESTR("da2", 3, "%s", u_dsc_algo[2])
+    else CASESTR("da3", 3, "%s", u_dsc_algo[3])
+    else CASESTR("odd_iv0", 7, "%s", u_odd_iv[0])
+    else CASESTR("odd_iv1", 7, "%s", u_odd_iv[1])
+    else CASESTR("odd_iv2", 7, "%s", u_odd_iv[2])
+    else CASESTR("odd_iv3", 7, "%s", u_odd_iv[3])
+    else CASESTR("odd_key0", 8, "%s", u_odd_key[0])
+    else CASESTR("odd_key1", 8, "%s", u_odd_key[1])
+    else CASESTR("odd_key2", 8, "%s", u_odd_key[2])
+    else CASESTR("odd_key3", 8, "%s", u_odd_key[3])
+    else CASESTR("even_iv0", 8, "%s", u_even_iv[0])
+    else CASESTR("even_iv1", 8, "%s", u_even_iv[1])
+    else CASESTR("even_iv2", 8, "%s", u_even_iv[2])
+    else CASESTR("even_iv3", 8, "%s", u_even_iv[3])
+    else CASESTR("even_key0", 9, "%s", u_even_key[0])
+    else CASESTR("even_key1", 9, "%s", u_even_key[1])
+    else CASESTR("even_key2", 9, "%s", u_even_key[2])
+    else CASESTR("even_key3", 9, "%s", u_even_key[3])
+    else CASESTR("00_iv0", 6, "%s", u_00_iv[0])
+    else CASESTR("00_iv1", 6, "%s", u_00_iv[1])
+    else CASESTR("00_iv2", 6, "%s", u_00_iv[2])
+    else CASESTR("00_iv3", 6, "%s", u_00_iv[3])
+    else CASESTR("00_key0", 7, "%s", u_00_key[0])
+    else CASESTR("00_key1", 7, "%s", u_00_key[1])
+    else CASESTR("00_key2", 7, "%s", u_00_key[2])
+    else CASESTR("00_key3", 7, "%s", u_00_key[3])
+    else CASE("bs0", 3, "%i", u_bs[0])
+    else CASE("bs1", 3, "%i", u_bs[1])
+    else CASE("bs2", 3, "%i", u_bs[2])
+    else CASE("bs3", 3, "%i", u_bs[3])
+    else CASE("bs4", 3, "%i", u_bs[4])
+    else CASE("para", 4, "%x", u_para_g)
+    else CASESTR("path", 4, "%s", u_path_g)
+    else CASESTR("input", 4, "%s", u_input_g)
 
-	if (u_path_g) {
-		char *e = strchr(u_path_g, ' ');
-		if (e) {
-			int l = e - u_path_g;
-			memcpy(u_path_g_b, u_path_g, l);
-			u_path_g_b[l] = '\0';
-			u_path_g = u_path_g_b;
-		}
-	}
+    if (u_path_g) {
+        char *e = strchr(u_path_g, ' ');
+        if (e) {
+            int l = e - u_path_g;
+            memcpy(u_path_g_b, u_path_g, l);
+            u_path_g_b[l] = '\0';
+            u_path_g = u_path_g_b;
+        }
+    }
 
-	if (u_input_g) {
-		memcpy(u_input_g_file, u_input_g+1, strlen(u_input_g)-1);
-	}
+    if (u_input_g) {
+        memcpy(u_input_g_file, u_input_g + 1, strlen(u_input_g) - 1);
+    }
 
-	return 0;
+    return 0;
 }
 
 int main(int argc, char **argv)
 {
-	AM_DMX_OpenPara_t para;
-//	AM_FEND_OpenPara_t fpara;
-//	struct dvb_frontend_parameters p;
-//	fe_status_t status;
-	int ret=0;
-	int i;
+    AM_DMX_OpenPara_t para;
+//    AM_FEND_OpenPara_t fend_para;
+//    struct dvb_frontend_parameters p;
+//    fe_status_t status;
+    int ret = 0;
+    int i;
 
-//	memset(&fpara, 0, sizeof(fpara));
+//    memset(&fend_para, 0, sizeof(fend_para));
 
-	if(argc==1)
-	{
-		printf(
-			"Usage:%s [freq=] [src=] [dmx=] [layer=] [timeout=] [pat=] [eit=] [bat=] [nit=] [pidx=] [parax=] [para=] [extx=] [bsx=] [out=]\n"
-			"  default   - src:0 dmx:0 layer:-1 parax:0\n"
-			"  x         - 0~4\n"
-			"  para      - d6->|111111|<-d1\n"
-			"    d1 - 0:sec 1:pes (means enable for pat/eit/bat/nit)\n"
-			"    d2 - 1:crc : sec only\n"
-			"    d3 - 1:print\n"
-			"    d4 - 1:swfilter\n"
-			"    d5 - 1:ts tap : pes only\n"
-			"    d6 - 1:w2file\n"
-			"    d7 - 1:convert pes to es format, pes only\n"
-			"  ext       - tid....\n"
-			"    eg. 0x82:0xff,0x02:0xff\n"
-			"    up to 16 filter data:mask(s)\n"
-			"  bs        - buffersize\n"
-			"  path      - output path\n"
-			, argv[0]);
-		return 0;
-	}
+    if (argc == 1)
+    {
+        printf(
+            "Usage:%s [freq=] [src=] [dmx=] [layer=] [timeout=] [pat=] [eit=] [bat=] [nit=] [pidx=] [parax=] [para=] [extx=] [bsx=] [out=]\n"
+            "  default   - src:0 dmx:0 layer:-1 parax:0\n"
+            "  x         - 0~4\n"
+            "  para      - d6->|111111|<-d1\n"
+            "    d1 - 0:sec 1:pes (means enable for pat/eit/bat/nit)\n"
+            "    d2 - 1:crc : sec only\n"
+            "    d3 - 1:print\n"
+            "    d4 - 1:swfilter\n"
+            "    d5 - 1:ts tap : pes only\n"
+            "    d6 - 1:w2file\n"
+            "    d7 - 1:convert pes to es format, pes only\n"
+            "  ext       - tid....\n"
+            "    eg. 0x82:0xff,0x02:0xff\n"
+            "    up to 16 filter data:mask(s)\n"
+            "  bs        - buffersize\n"
+            "  path      - output path\n"
+            , argv[0]);
+        return 0;
+    }
 
-	for(i=1; i< argc; i++)
-		get_para(argv[i]);
+    for (i = 1; i < argc; i++)
+        get_para(argv[i]);
 
-	memset(&para, 0, sizeof(para));
-	//para.use_sw_filter = AM_TRUE;
-	//para.dvr_fifo_no = 1;
-	AM_TRY(AM_DMX_Open(dmx, &para));
+    memset(&para, 0, sizeof(para));
+    //para.use_sw_filter = AM_TRUE;
+    //para.dvr_fifo_no = 1;
+    AM_TRY(AM_DMX_Open(dmx, &para));
 
-	if (u_input_g) {
-		AM_DMX_SetInput(dmx, INPUT_LOCAL);
-	}
+    if (u_input_g) {
+        AM_DMX_SetInput(dmx, INPUT_LOCAL);
+    }
 
-	memset(&key_index, -1, sizeof(key_index));
+    memset(&key_index, -1, sizeof(key_index));
 
-	get_section(dmx, timeout);
+    get_section(dmx, timeout);
 
-	AM_DMX_Close(dmx);
+    AM_DMX_Close(dmx);
 
-	if (src == 1 && u_input_g)
-		inject_file_and_rec_close();
-	return ret;
+    if (src == 1 && u_input_g)
+        inject_file_and_rec_close();
+    return ret;
 }
 
diff --git a/test/am_ca_test/am_dmx.c b/test/am_ca_test/am_dmx.c
index ff82947..0b4997b 100644
--- a/test/am_ca_test/am_dmx.c
+++ b/test/am_ca_test/am_dmx.c
@@ -88,17 +88,17 @@
 #endif
 };
 static void init_dmx_dev() {
-	static int init_dmx_dev_flag = 0;
-	int i = 0;
+    static int init_dmx_dev_flag = 0;
+    int i = 0;
 
-	if (!init_dmx_dev_flag) {
-		init_dmx_dev_flag = 1;
+    if (!init_dmx_dev_flag) {
+        init_dmx_dev_flag = 1;
 
-		for (i = 0; i < DMX_DEV_COUNT; i++) {
-			dmx_devices[i].drv = &linux_dvb_dmx_drv;
-			dmx_devices[i].src = AM_DMX_SRC_TS0;
-		}
-	}
+        for (i = 0; i < DMX_DEV_COUNT; i++) {
+            dmx_devices[i].drv = &linux_dvb_dmx_drv;
+            dmx_devices[i].src = AM_DMX_SRC_TS0;
+        }
+    }
 }
 /****************************************************************************
  * Static functions
@@ -107,222 +107,222 @@
 /**\brief 根据设备号取得设备结构指针*/
 static AM_INLINE AM_ErrorCode_t dmx_get_dev(int dev_no, AM_DMX_Device_t **dev)
 {
-	if((dev_no < 0) || (dev_no >= DMX_DEV_COUNT))
-	{
-		printf("invalid demux device number %d, must in(%d~%d)", dev_no, 0, DMX_DEV_COUNT-1);
-		return AM_DMX_ERR_INVALID_DEV_NO;
-	}
+    if ((dev_no < 0) || (dev_no >= DMX_DEV_COUNT))
+    {
+        printf("invalid demux device number %d, must in(%d~%d)", dev_no, 0, DMX_DEV_COUNT-1);
+        return AM_DMX_ERR_INVALID_DEV_NO;
+    }
 
-	*dev = &dmx_devices[dev_no];
-	return AM_SUCCESS;
+    *dev = &dmx_devices[dev_no];
+    return AM_SUCCESS;
 }
 
 /**\brief 根据设备号取得设备结构并检查设备是否已经打开*/
 static AM_INLINE AM_ErrorCode_t dmx_get_openned_dev(int dev_no, AM_DMX_Device_t **dev)
 {
-	AM_TRY(dmx_get_dev(dev_no, dev));
+    AM_TRY(dmx_get_dev(dev_no, dev));
 
-	if((*dev)->open_count <= 0)
-	{
-		printf("demux device %d has not been openned", dev_no);
-		return AM_DMX_ERR_INVALID_DEV_NO;
-	}
+    if ((*dev)->open_count <= 0)
+    {
+        printf("demux device %d has not been openned", dev_no);
+        return AM_DMX_ERR_INVALID_DEV_NO;
+    }
 
-	return AM_SUCCESS;
+    return AM_SUCCESS;
 }
 
 /**\brief 根据ID取得对应filter结构,并检查设备是否在使用*/
 static AM_INLINE AM_ErrorCode_t dmx_get_used_filter(AM_DMX_Device_t *dev, int filter_id, AM_DMX_Filter_t **pf)
 {
-	AM_DMX_Filter_t *filter;
+    AM_DMX_Filter_t *filter;
 
-	if((filter_id<0) || (filter_id>=DMX_FILTER_COUNT))
-	{
-		printf("invalid filter id, must in %d~%d", 0, DMX_FILTER_COUNT-1);
-		return AM_DMX_ERR_INVALID_ID;
-	}
+    if ((filter_id < 0) || (filter_id >= DMX_FILTER_COUNT))
+    {
+        printf("invalid filter id, must in %d~%d", 0, DMX_FILTER_COUNT-1);
+        return AM_DMX_ERR_INVALID_ID;
+    }
 
-	filter = &dev->filters[filter_id];
+    filter = &dev->filters[filter_id];
 
-	if(!filter->used)
-	{
-		printf("filter %d has not been allocated", filter_id);
-		return AM_DMX_ERR_NOT_ALLOCATED;
-	}
+    if (!filter->used)
+    {
+        printf("filter %d has not been allocated", filter_id);
+        return AM_DMX_ERR_NOT_ALLOCATED;
+    }
 
-	*pf = filter;
-	return AM_SUCCESS;
+    *pf = filter;
+    return AM_SUCCESS;
 }
 
 /**\brief 数据检测线程*/
 static void* dmx_data_thread(void *arg)
 {
-	AM_DMX_Device_t *dev = (AM_DMX_Device_t*)arg;
-	uint8_t *sec_buf;
-	uint8_t *sec;
-	int sec_len;
-	AM_DMX_FilterMask_t mask;
-	AM_ErrorCode_t ret;
+    AM_DMX_Device_t *dev = (AM_DMX_Device_t*)arg;
+    uint8_t *sec_buf;
+    uint8_t *sec;
+    int sec_len;
+    AM_DMX_FilterMask_t mask;
+    AM_ErrorCode_t ret;
 
 #define BUF_SIZE (4096)
 
-	sec_buf = (uint8_t*)malloc(BUF_SIZE);
+    sec_buf = (uint8_t*)malloc(BUF_SIZE);
 
-	while(dev->enable_thread)
-	{
-		AM_DMX_FILTER_MASK_CLEAR(&mask);
-		int id;
+    while (dev->enable_thread)
+    {
+        AM_DMX_FILTER_MASK_CLEAR(&mask);
+        int id;
 
-		ret = dev->drv->poll(dev, &mask, DMX_POLL_TIMEOUT);
-		if(ret==AM_SUCCESS)
-		{
-			if(AM_DMX_FILTER_MASK_ISEMPTY(&mask))
-				continue;
+        ret = dev->drv->poll(dev, &mask, DMX_POLL_TIMEOUT);
+        if (ret == AM_SUCCESS)
+        {
+            if (AM_DMX_FILTER_MASK_ISEMPTY(&mask))
+                continue;
 
 #if defined(DMX_WAIT_CB) || defined(DMX_SYNC)
-			pthread_mutex_lock(&dev->lock);
-			dev->flags |= DMX_FL_RUN_CB;
-			pthread_mutex_unlock(&dev->lock);
+            pthread_mutex_lock(&dev->lock);
+            dev->flags |= DMX_FL_RUN_CB;
+            pthread_mutex_unlock(&dev->lock);
 #endif
 
-			for(id=0; id<DMX_FILTER_COUNT; id++)
-			{
-				AM_DMX_Filter_t *filter=&dev->filters[id];
-				AM_DMX_DataCb cb;
-				void *data;
+            for (id = 0; id < DMX_FILTER_COUNT; id++)
+            {
+                AM_DMX_Filter_t *filter=&dev->filters[id];
+                AM_DMX_DataCb cb;
+                void *data;
 
-				if(!AM_DMX_FILTER_MASK_ISSET(&mask, id))
-					continue;
-				
-				if(!filter->enable || !filter->used)
-					continue;
-				sec_len = BUF_SIZE;
+                if (!AM_DMX_FILTER_MASK_ISSET(&mask, id))
+                    continue;
+
+                if (!filter->enable || !filter->used)
+                    continue;
+                sec_len = BUF_SIZE;
 
 #ifndef DMX_WAIT_CB
-				pthread_mutex_lock(&dev->lock);
+                pthread_mutex_lock(&dev->lock);
 #endif
-				if(!filter->enable || !filter->used)
-				{
-					ret = AM_FAILURE;
-				}
-				else
-				{
-					cb   = filter->cb;
-					data = filter->user_data;
-					ret  = dev->drv->read(dev, filter, sec_buf, &sec_len);
-				}
+                if (!filter->enable || !filter->used)
+                {
+                    ret = AM_FAILURE;
+                }
+                else
+                {
+                    cb   = filter->cb;
+                    data = filter->user_data;
+                    ret  = dev->drv->read(dev, filter, sec_buf, &sec_len);
+                }
 #ifndef DMX_WAIT_CB
-				pthread_mutex_unlock(&dev->lock);
+                pthread_mutex_unlock(&dev->lock);
 #endif
-				if(ret==AM_DMX_ERR_TIMEOUT)
-				{
-					sec = NULL;
-					sec_len = 0;
-				}
-				else if(ret!=AM_SUCCESS)
-				{
-					continue;
-				}
-				else
-				{
-					sec = sec_buf;
-				}
+                if (ret == AM_DMX_ERR_TIMEOUT)
+                {
+                    sec = NULL;
+                    sec_len = 0;
+                }
+                else if (ret != AM_SUCCESS)
+                {
+                    continue;
+                }
+                else
+                {
+                    sec = sec_buf;
+                }
 
-				if(cb)
-				{
-					if(id && sec)
-					printf("filter %d data callback len fd:%ld len:%d, %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x",
-						id, (long)filter->drv_data, sec_len,
-						sec[0], sec[1], sec[2], sec[3], sec[4],
-						sec[5], sec[6], sec[7], sec[8], sec[9]);
-					cb(dev->dev_no, id, sec, sec_len, data);
-					if(id && sec)
-					printf("filter %d data callback ok", id);
-				}
-			}
+                if (cb)
+                {
+                    if (id && sec)
+                    printf("filter %d data callback len fd:%ld len:%d, %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x",
+                        id, (long)filter->drv_data, sec_len,
+                        sec[0], sec[1], sec[2], sec[3], sec[4],
+                        sec[5], sec[6], sec[7], sec[8], sec[9]);
+                    cb(dev->dev_no, id, sec, sec_len, data);
+                    if (id && sec)
+                    printf("filter %d data callback ok", id);
+                }
+            }
 #if defined(DMX_WAIT_CB) || defined(DMX_SYNC)
-			pthread_mutex_lock(&dev->lock);
-			dev->flags &= ~DMX_FL_RUN_CB;
-			pthread_mutex_unlock(&dev->lock);
-			pthread_cond_broadcast(&dev->cond);
+            pthread_mutex_lock(&dev->lock);
+            dev->flags &= ~DMX_FL_RUN_CB;
+            pthread_mutex_unlock(&dev->lock);
+            pthread_cond_broadcast(&dev->cond);
 #endif
-		}
-		else
-		{
-			usleep(10000);
-		}
-	}
+        }
+        else
+        {
+            usleep(10000);
+        }
+    }
 
-	if(sec_buf)
-	{
-		free(sec_buf);
-	}
+    if (sec_buf)
+    {
+        free(sec_buf);
+    }
 
-	return NULL;
+    return NULL;
 }
 
 /**\brief 等待回调函数停止运行*/
 static AM_INLINE AM_ErrorCode_t dmx_wait_cb(AM_DMX_Device_t *dev)
 {
 #ifdef DMX_WAIT_CB
-	if(dev->thread!=pthread_self())
-	{
-		while(dev->flags&DMX_FL_RUN_CB)
-			pthread_cond_wait(&dev->cond, &dev->lock);
-	}
+    if (dev->thread != pthread_self())
+    {
+        while (dev->flags & DMX_FL_RUN_CB)
+            pthread_cond_wait(&dev->cond, &dev->lock);
+    }
 #else
-	UNUSED(dev);
+    UNUSED(dev);
 #endif
-	return AM_SUCCESS;
+    return AM_SUCCESS;
 }
 
 /**\brief 停止Section过滤器*/
 static AM_ErrorCode_t dmx_stop_filter(AM_DMX_Device_t *dev, AM_DMX_Filter_t *filter)
 {
-	AM_ErrorCode_t ret = AM_SUCCESS;
+    AM_ErrorCode_t ret = AM_SUCCESS;
 
-	if(!filter->used || !filter->enable)
-	{
-		return ret;
-	}
+    if (!filter->used || !filter->enable)
+    {
+        return ret;
+    }
 
-	if(dev->drv->enable_filter)
-	{
-		ret = dev->drv->enable_filter(dev, filter, AM_FALSE);
-	}
+    if (dev->drv->enable_filter)
+    {
+        ret = dev->drv->enable_filter(dev, filter, AM_FALSE);
+    }
 
-	if(ret>=0)
-	{
-		filter->enable = AM_FALSE;
-	}
+    if (ret >= 0)
+    {
+        filter->enable = AM_FALSE;
+    }
 
-	return ret;
+    return ret;
 }
 
 /**\brief 释放过滤器*/
 static int dmx_free_filter(AM_DMX_Device_t *dev, AM_DMX_Filter_t *filter)
 {
-	AM_ErrorCode_t ret = AM_SUCCESS;
+    AM_ErrorCode_t ret = AM_SUCCESS;
 
-	if(!filter->used)
-		return ret;
+    if (!filter->used)
+        return ret;
 
-	ret = dmx_stop_filter(dev, filter);
+    ret = dmx_stop_filter(dev, filter);
 
-	if(ret==AM_SUCCESS)
-	{
-		if(dev->drv->free_filter)
-		{
-			ret = dev->drv->free_filter(dev, filter);
-		}
-	}
+    if (ret == AM_SUCCESS)
+    {
+        if (dev->drv->free_filter)
+        {
+            ret = dev->drv->free_filter(dev, filter);
+        }
+    }
 
-	if(ret==AM_SUCCESS)
-	{
-		filter->used=AM_FALSE;
-	}
+    if (ret == AM_SUCCESS)
+    {
+        filter->used = AM_FALSE;
+    }
 
-	return ret;
+    return ret;
 }
 
 /****************************************************************************
@@ -338,61 +338,61 @@
  */
 AM_ErrorCode_t AM_DMX_Open(int dev_no, const AM_DMX_OpenPara_t *para)
 {
-	AM_DMX_Device_t *dev;
-	AM_ErrorCode_t ret = AM_SUCCESS;
+    AM_DMX_Device_t *dev;
+    AM_ErrorCode_t ret = AM_SUCCESS;
 
-	assert(para);
+    assert(para);
 
-	init_dmx_dev();
+    init_dmx_dev();
 
-	AM_TRY(dmx_get_dev(dev_no, &dev));
+    AM_TRY(dmx_get_dev(dev_no, &dev));
 
-//	pthread_mutex_lock(&am_gAdpLock);
+//    pthread_mutex_lock(&am_gAdpLock);
 
-	if(dev->open_count > 0)
-	{
-		printf("demux device %d has already been openned", dev_no);
-		dev->open_count++;
-		ret = AM_SUCCESS;
-		goto final;
-	}
+    if (dev->open_count > 0)
+    {
+        printf("demux device %d has already been openned", dev_no);
+        dev->open_count++;
+        ret = AM_SUCCESS;
+        goto final;
+    }
 
-	dev->dev_no = dev_no;
+    dev->dev_no = dev_no;
 
-	if(para->use_sw_filter){
-//		dev->drv = &SW_DMX_DRV;
-	}else{
-		dev->drv = &HW_DMX_DRV;
-	}
+    if (para->use_sw_filter) {
+//        dev->drv = &SW_DMX_DRV;
+    } else {
+        dev->drv = &HW_DMX_DRV;
+    }
 
-	if(dev->drv->open)
-	{
-		ret = dev->drv->open(dev, para);
-	}
+    if (dev->drv->open)
+    {
+        ret = dev->drv->open(dev, para);
+    }
 
-	if(ret==AM_SUCCESS)
-	{
-		pthread_mutex_init(&dev->lock, NULL);
-		pthread_cond_init(&dev->cond, NULL);
-		dev->enable_thread = AM_TRUE;
-		dev->flags = 0;
+    if (ret == AM_SUCCESS)
+    {
+        pthread_mutex_init(&dev->lock, NULL);
+        pthread_cond_init(&dev->cond, NULL);
+        dev->enable_thread = AM_TRUE;
+        dev->flags = 0;
 
-		if(pthread_create(&dev->thread, NULL, dmx_data_thread, dev))
-		{
-			pthread_mutex_destroy(&dev->lock);
-			pthread_cond_destroy(&dev->cond);
-			ret = AM_DMX_ERR_CANNOT_CREATE_THREAD;
-		}
-	}
+        if (pthread_create(&dev->thread, NULL, dmx_data_thread, dev))
+        {
+            pthread_mutex_destroy(&dev->lock);
+            pthread_cond_destroy(&dev->cond);
+            ret = AM_DMX_ERR_CANNOT_CREATE_THREAD;
+        }
+    }
 
-	if(ret==AM_SUCCESS)
-	{
-		dev->open_count = 1;
-	}
+    if (ret == AM_SUCCESS)
+    {
+        dev->open_count = 1;
+    }
 final:
-//	pthread_mutex_unlock(&am_gAdpLock);
+//    pthread_mutex_unlock(&am_gAdpLock);
 
-	return ret;
+    return ret;
 }
 
 /**\brief 关闭解复用设备
@@ -403,37 +403,37 @@
  */
 AM_ErrorCode_t AM_DMX_Close(int dev_no)
 {
-	AM_DMX_Device_t *dev;
-	AM_ErrorCode_t ret = AM_SUCCESS;
-	int i;
+    AM_DMX_Device_t *dev;
+    AM_ErrorCode_t ret = AM_SUCCESS;
+    int i;
 
-	AM_TRY(dmx_get_openned_dev(dev_no, &dev));
+    AM_TRY(dmx_get_openned_dev(dev_no, &dev));
 
-//	pthread_mutex_lock(&am_gAdpLock);
+//    pthread_mutex_lock(&am_gAdpLock);
 
-	if (dev->open_count == 1)
-	{
-		dev->enable_thread = AM_FALSE;
-		pthread_join(dev->thread, NULL);
+    if (dev->open_count == 1)
+    {
+        dev->enable_thread = AM_FALSE;
+        pthread_join(dev->thread, NULL);
 
-		for(i=0; i<DMX_FILTER_COUNT; i++)
-		{
-			dmx_free_filter(dev, &dev->filters[i]);
-		}
+        for (i = 0; i < DMX_FILTER_COUNT; i++)
+        {
+            dmx_free_filter(dev, &dev->filters[i]);
+        }
 
-		if(dev->drv->close)
-		{
-			dev->drv->close(dev);
-		}
+        if (dev->drv->close)
+        {
+            dev->drv->close(dev);
+        }
 
-		pthread_mutex_destroy(&dev->lock);
-		pthread_cond_destroy(&dev->cond);
-	}
-	dev->open_count--;
+        pthread_mutex_destroy(&dev->lock);
+        pthread_cond_destroy(&dev->cond);
+    }
+    dev->open_count--;
 
-//	pthread_mutex_unlock(&am_gAdpLock);
+//    pthread_mutex_unlock(&am_gAdpLock);
 
-	return ret;
+    return ret;
 }
 
 /**\brief 分配一个过滤器
@@ -445,48 +445,48 @@
  */
 AM_ErrorCode_t AM_DMX_AllocateFilter(int dev_no, int *fhandle)
 {
-	AM_DMX_Device_t *dev;
-	AM_ErrorCode_t ret = AM_SUCCESS;
-	int fid;
+    AM_DMX_Device_t *dev;
+    AM_ErrorCode_t ret = AM_SUCCESS;
+    int fid;
 
-	assert(fhandle);
+    assert(fhandle);
 
-	AM_TRY(dmx_get_openned_dev(dev_no, &dev));
+    AM_TRY(dmx_get_openned_dev(dev_no, &dev));
 
-	pthread_mutex_lock(&dev->lock);
+    pthread_mutex_lock(&dev->lock);
 
-	for(fid=0; fid<DMX_FILTER_COUNT; fid++)
-	{
-		if(!dev->filters[fid].used)
-			break;
-	}
+    for (fid = 0; fid < DMX_FILTER_COUNT; fid++)
+    {
+        if (!dev->filters[fid].used)
+            break;
+    }
 
-	if(fid>=DMX_FILTER_COUNT)
-	{
-		printf("no free section filter");
-		ret = AM_DMX_ERR_NO_FREE_FILTER;
-	}
+    if (fid >= DMX_FILTER_COUNT)
+    {
+        printf("no free section filter");
+        ret = AM_DMX_ERR_NO_FREE_FILTER;
+    }
 
-	if(ret==AM_SUCCESS)
-	{
-		dmx_wait_cb(dev);
+    if (ret == AM_SUCCESS)
+    {
+        dmx_wait_cb(dev);
 
-		dev->filters[fid].id   = fid;
-		if(dev->drv->alloc_filter)
-		{
-			ret = dev->drv->alloc_filter(dev, &dev->filters[fid]);
-		}
-	}
+        dev->filters[fid].id   = fid;
+        if (dev->drv->alloc_filter)
+        {
+            ret = dev->drv->alloc_filter(dev, &dev->filters[fid]);
+        }
+    }
 
-	if(ret==AM_SUCCESS)
-	{
-		dev->filters[fid].used = AM_TRUE;
-		*fhandle = fid;
-	}
+    if (ret == AM_SUCCESS)
+    {
+        dev->filters[fid].used = AM_TRUE;
+        *fhandle = fid;
+    }
 
-	pthread_mutex_unlock(&dev->lock);
+    pthread_mutex_unlock(&dev->lock);
 
-	return ret;
+    return ret;
 }
 
 /**\brief 设定Section过滤器
@@ -499,48 +499,48 @@
  */
 AM_ErrorCode_t AM_DMX_SetSecFilter(int dev_no, int fhandle, const struct dmx_sct_filter_params *params)
 {
-	AM_DMX_Device_t *dev;
-	AM_DMX_Filter_t *filter;
-	AM_ErrorCode_t ret = AM_SUCCESS;
+    AM_DMX_Device_t *dev;
+    AM_DMX_Filter_t *filter;
+    AM_ErrorCode_t ret = AM_SUCCESS;
 
-	assert(params);
+    assert(params);
 
-	AM_TRY(dmx_get_openned_dev(dev_no, &dev));
+    AM_TRY(dmx_get_openned_dev(dev_no, &dev));
 
-	if(!dev->drv->set_sec_filter)
-	{
-		printf("demux do not support set_sec_filter");
-		return AM_DMX_ERR_NOT_SUPPORTED;
-	}
+    if (!dev->drv->set_sec_filter)
+    {
+        printf("demux do not support set_sec_filter");
+        return AM_DMX_ERR_NOT_SUPPORTED;
+    }
 
-	pthread_mutex_lock(&dev->lock);
+    pthread_mutex_lock(&dev->lock);
 
-	ret = dmx_get_used_filter(dev, fhandle, &filter);
+    ret = dmx_get_used_filter(dev, fhandle, &filter);
 
-	if(ret==AM_SUCCESS)
-	{
-		dmx_wait_cb(dev);
-		ret = dmx_stop_filter(dev, filter);
-	}
+    if (ret == AM_SUCCESS)
+    {
+        dmx_wait_cb(dev);
+        ret = dmx_stop_filter(dev, filter);
+    }
 
-	if(ret==AM_SUCCESS)
-	{
-		ret = dev->drv->set_sec_filter(dev, filter, params);
-		printf("set sec filter %d PID: %d filter: %02x:%02x %02x:%02x %02x:%02x %02x:%02x %02x:%02x %02x:%02x %02x:%02x %02x:%02x",
-				fhandle, params->pid,
-				params->filter.filter[0], params->filter.mask[0],
-				params->filter.filter[1], params->filter.mask[1],
-				params->filter.filter[2], params->filter.mask[2],
-				params->filter.filter[3], params->filter.mask[3],
-				params->filter.filter[4], params->filter.mask[4],
-				params->filter.filter[5], params->filter.mask[5],
-				params->filter.filter[6], params->filter.mask[6],
-				params->filter.filter[7], params->filter.mask[7]);
-	}
+    if (ret == AM_SUCCESS)
+    {
+        ret = dev->drv->set_sec_filter(dev, filter, params);
+        printf("set sec filter %d PID: %d filter: %02x:%02x %02x:%02x %02x:%02x %02x:%02x %02x:%02x %02x:%02x %02x:%02x %02x:%02x",
+                fhandle, params->pid,
+                params->filter.filter[0], params->filter.mask[0],
+                params->filter.filter[1], params->filter.mask[1],
+                params->filter.filter[2], params->filter.mask[2],
+                params->filter.filter[3], params->filter.mask[3],
+                params->filter.filter[4], params->filter.mask[4],
+                params->filter.filter[5], params->filter.mask[5],
+                params->filter.filter[6], params->filter.mask[6],
+                params->filter.filter[7], params->filter.mask[7]);
+    }
 
-	pthread_mutex_unlock(&dev->lock);
+    pthread_mutex_unlock(&dev->lock);
 
-	return ret;
+    return ret;
 }
 
 /**\brief 设定PES过滤器
@@ -553,67 +553,67 @@
  */
 AM_ErrorCode_t AM_DMX_SetPesFilter(int dev_no, int fhandle, const struct dmx_pes_filter_params *params)
 {
-	AM_DMX_Device_t *dev;
-	AM_DMX_Filter_t *filter;
-	AM_ErrorCode_t ret = AM_SUCCESS;
+    AM_DMX_Device_t *dev;
+    AM_DMX_Filter_t *filter;
+    AM_ErrorCode_t ret = AM_SUCCESS;
 
-	assert(params);
+    assert(params);
 
-	AM_TRY(dmx_get_openned_dev(dev_no, &dev));
+    AM_TRY(dmx_get_openned_dev(dev_no, &dev));
 
-	if(!dev->drv->set_pes_filter)
-	{
-		printf("demux do not support set_pes_filter");
-		return AM_DMX_ERR_NOT_SUPPORTED;
-	}
+    if (!dev->drv->set_pes_filter)
+    {
+        printf("demux do not support set_pes_filter");
+        return AM_DMX_ERR_NOT_SUPPORTED;
+    }
 
-	pthread_mutex_lock(&dev->lock);
+    pthread_mutex_lock(&dev->lock);
 
-	ret = dmx_get_used_filter(dev, fhandle, &filter);
+    ret = dmx_get_used_filter(dev, fhandle, &filter);
 
-	if(ret==AM_SUCCESS)
-	{
-		dmx_wait_cb(dev);
-		ret = dmx_stop_filter(dev, filter);
-	}
+    if (ret == AM_SUCCESS)
+    {
+        dmx_wait_cb(dev);
+        ret = dmx_stop_filter(dev, filter);
+    }
 
-	if(ret==AM_SUCCESS)
-	{
-		ret = dev->drv->set_pes_filter(dev, filter, params);
-		printf("set pes filter %d PID %d", fhandle, params->pid);
-	}
+    if (ret == AM_SUCCESS)
+    {
+        ret = dev->drv->set_pes_filter(dev, filter, params);
+        printf("set pes filter %d PID %d", fhandle, params->pid);
+    }
 
-	pthread_mutex_unlock(&dev->lock);
+    pthread_mutex_unlock(&dev->lock);
 
-	return ret;
+    return ret;
 }
 AM_ErrorCode_t AM_DMX_GetSTC(int dev_no, int fhandle)
 {
-	AM_DMX_Device_t *dev;
-	AM_DMX_Filter_t *filter;
-	AM_ErrorCode_t ret = AM_SUCCESS;
+    AM_DMX_Device_t *dev;
+    AM_DMX_Filter_t *filter;
+    AM_ErrorCode_t ret = AM_SUCCESS;
 
-	AM_TRY(dmx_get_openned_dev(dev_no, &dev));
-	printf("%s line:%d\n", __FUNCTION__, __LINE__);
-	if(!dev->drv->get_stc)
-	{
-		printf("demux do not support set_pes_filter");
-		return AM_DMX_ERR_NOT_SUPPORTED;
-	}
+    AM_TRY(dmx_get_openned_dev(dev_no, &dev));
+    printf("%s line:%d\n", __FUNCTION__, __LINE__);
+    if (!dev->drv->get_stc)
+    {
+        printf("demux do not support set_pes_filter");
+        return AM_DMX_ERR_NOT_SUPPORTED;
+    }
 
-	pthread_mutex_lock(&dev->lock);
+    pthread_mutex_lock(&dev->lock);
 
-	ret = dmx_get_used_filter(dev, fhandle, &filter);
+    ret = dmx_get_used_filter(dev, fhandle, &filter);
 
-	if(ret==AM_SUCCESS)
-	{
-		ret = dev->drv->get_stc(dev, filter);
-	}
+    if (ret == AM_SUCCESS)
+    {
+        ret = dev->drv->get_stc(dev, filter);
+    }
 
-	pthread_mutex_unlock(&dev->lock);
-	printf("%s line:%d\n", __FUNCTION__, __LINE__);
+    pthread_mutex_unlock(&dev->lock);
+    printf("%s line:%d\n", __FUNCTION__, __LINE__);
 
-	return ret;
+    return ret;
 }
 
 
@@ -626,25 +626,25 @@
  */
 AM_ErrorCode_t AM_DMX_FreeFilter(int dev_no, int fhandle)
 {
-	AM_DMX_Device_t *dev;
-	AM_DMX_Filter_t *filter;
-	AM_ErrorCode_t ret = AM_SUCCESS;
+    AM_DMX_Device_t *dev;
+    AM_DMX_Filter_t *filter;
+    AM_ErrorCode_t ret = AM_SUCCESS;
 
-	AM_TRY(dmx_get_openned_dev(dev_no, &dev));
+    AM_TRY(dmx_get_openned_dev(dev_no, &dev));
 
-	pthread_mutex_lock(&dev->lock);
+    pthread_mutex_lock(&dev->lock);
 
-	ret = dmx_get_used_filter(dev, fhandle, &filter);
+    ret = dmx_get_used_filter(dev, fhandle, &filter);
 
-	if(ret==AM_SUCCESS)
-	{
-		dmx_wait_cb(dev);
-		ret = dmx_free_filter(dev, filter);
-	}
+    if (ret == AM_SUCCESS)
+    {
+        dmx_wait_cb(dev);
+        ret = dmx_free_filter(dev, filter);
+    }
 
-	pthread_mutex_unlock(&dev->lock);
+    pthread_mutex_unlock(&dev->lock);
 
-	return ret;
+    return ret;
 }
 
 /**\brief 让一个过滤器开始运行
@@ -656,35 +656,35 @@
  */
 AM_ErrorCode_t AM_DMX_StartFilter(int dev_no, int fhandle)
 {
-	AM_DMX_Device_t *dev;
-	AM_DMX_Filter_t *filter = NULL;
-	AM_ErrorCode_t ret = AM_SUCCESS;
+    AM_DMX_Device_t *dev;
+    AM_DMX_Filter_t *filter = NULL;
+    AM_ErrorCode_t ret = AM_SUCCESS;
 
-	AM_TRY(dmx_get_openned_dev(dev_no, &dev));
+    AM_TRY(dmx_get_openned_dev(dev_no, &dev));
 
-	pthread_mutex_lock(&dev->lock);
+    pthread_mutex_lock(&dev->lock);
 
-	ret = dmx_get_used_filter(dev, fhandle, &filter);
+    ret = dmx_get_used_filter(dev, fhandle, &filter);
 
-	if(!filter->enable)
-	{
-		if(ret==AM_SUCCESS)
-		{
-			if(dev->drv->enable_filter)
-			{
-				ret = dev->drv->enable_filter(dev, filter, AM_TRUE);
-			}
-		}
+    if (!filter->enable)
+    {
+        if (ret == AM_SUCCESS)
+        {
+            if (dev->drv->enable_filter)
+            {
+                ret = dev->drv->enable_filter(dev, filter, AM_TRUE);
+            }
+        }
 
-		if(ret==AM_SUCCESS)
-		{
-			filter->enable = AM_TRUE;
-		}
-	}
+        if (ret == AM_SUCCESS)
+        {
+            filter->enable = AM_TRUE;
+        }
+    }
 
-	pthread_mutex_unlock(&dev->lock);
+    pthread_mutex_unlock(&dev->lock);
 
-	return ret;
+    return ret;
 }
 
 /**\brief 停止一个过滤器
@@ -696,27 +696,27 @@
  */
 AM_ErrorCode_t AM_DMX_StopFilter(int dev_no, int fhandle)
 {
-	AM_DMX_Device_t *dev;
-	AM_DMX_Filter_t *filter = NULL;
-	AM_ErrorCode_t ret = AM_SUCCESS;
+    AM_DMX_Device_t *dev;
+    AM_DMX_Filter_t *filter = NULL;
+    AM_ErrorCode_t ret = AM_SUCCESS;
 
-	AM_TRY(dmx_get_openned_dev(dev_no, &dev));
+    AM_TRY(dmx_get_openned_dev(dev_no, &dev));
 
-	pthread_mutex_lock(&dev->lock);
+    pthread_mutex_lock(&dev->lock);
 
-	ret = dmx_get_used_filter(dev, fhandle, &filter);
-	if(ret==AM_SUCCESS)
-	{
-		if(filter->enable)
-		{
-			dmx_wait_cb(dev);
-			ret = dmx_stop_filter(dev, filter);
-		}
-	}
+    ret = dmx_get_used_filter(dev, fhandle, &filter);
+    if (ret == AM_SUCCESS)
+    {
+        if (filter->enable)
+        {
+            dmx_wait_cb(dev);
+            ret = dmx_stop_filter(dev, filter);
+        }
+    }
 
-	pthread_mutex_unlock(&dev->lock);
+    pthread_mutex_unlock(&dev->lock);
 
-	return ret;
+    return ret;
 }
 
 /**\brief 设置一个过滤器的缓冲区大小
@@ -729,29 +729,29 @@
  */
 AM_ErrorCode_t AM_DMX_SetBufferSize(int dev_no, int fhandle, int size)
 {
-	AM_DMX_Device_t *dev;
-	AM_DMX_Filter_t *filter;
-	AM_ErrorCode_t ret = AM_SUCCESS;
+    AM_DMX_Device_t *dev;
+    AM_DMX_Filter_t *filter;
+    AM_ErrorCode_t ret = AM_SUCCESS;
 
-	AM_TRY(dmx_get_openned_dev(dev_no, &dev));
+    AM_TRY(dmx_get_openned_dev(dev_no, &dev));
 
-	pthread_mutex_lock(&dev->lock);
+    pthread_mutex_lock(&dev->lock);
 
-	if(!dev->drv->set_buf_size)
-	{
-		printf("do not support set_buf_size");
-		ret = AM_DMX_ERR_NOT_SUPPORTED;
-	}
+    if (!dev->drv->set_buf_size)
+    {
+        printf("do not support set_buf_size");
+        ret = AM_DMX_ERR_NOT_SUPPORTED;
+    }
 
-	if(ret==AM_SUCCESS)
-		ret = dmx_get_used_filter(dev, fhandle, &filter);
+    if (ret == AM_SUCCESS)
+        ret = dmx_get_used_filter(dev, fhandle, &filter);
 
-	if(ret==AM_SUCCESS)
-		ret = dev->drv->set_buf_size(dev, filter, size);
+    if (ret == AM_SUCCESS)
+        ret = dev->drv->set_buf_size(dev, filter, size);
 
-	pthread_mutex_unlock(&dev->lock);
+    pthread_mutex_unlock(&dev->lock);
 
-	return ret;
+    return ret;
 }
 
 /**\brief 取得一个过滤器对应的回调函数和用户参数
@@ -765,28 +765,28 @@
  */
 AM_ErrorCode_t AM_DMX_GetCallback(int dev_no, int fhandle, AM_DMX_DataCb *cb, void **data)
 {
-	AM_DMX_Device_t *dev;
-	AM_DMX_Filter_t *filter;
-	AM_ErrorCode_t ret = AM_SUCCESS;
+    AM_DMX_Device_t *dev;
+    AM_DMX_Filter_t *filter;
+    AM_ErrorCode_t ret = AM_SUCCESS;
 
-	AM_TRY(dmx_get_openned_dev(dev_no, &dev));
+    AM_TRY(dmx_get_openned_dev(dev_no, &dev));
 
-	pthread_mutex_lock(&dev->lock);
+    pthread_mutex_lock(&dev->lock);
 
-	ret = dmx_get_used_filter(dev, fhandle, &filter);
+    ret = dmx_get_used_filter(dev, fhandle, &filter);
 
-	if(ret==AM_SUCCESS)
-	{
-		if(cb)
-			*cb = filter->cb;
+    if (ret == AM_SUCCESS)
+    {
+        if (cb)
+            *cb = filter->cb;
 
-		if(data)
-			*data = filter->user_data;
-	}
+        if (data)
+            *data = filter->user_data;
+    }
 
-	pthread_mutex_unlock(&dev->lock);
+    pthread_mutex_unlock(&dev->lock);
 
-	return ret;
+    return ret;
 }
 
 /**\brief 设置一个过滤器对应的回调函数和用户参数
@@ -800,22 +800,22 @@
  */
 AM_ErrorCode_t AM_DMX_SetCallback(int dev_no, int fhandle, AM_DMX_DataCb cb, void *data)
 {
-	AM_DMX_Device_t *dev;
-	AM_DMX_Filter_t *filter;
-	AM_ErrorCode_t ret = AM_SUCCESS;
+    AM_DMX_Device_t *dev;
+    AM_DMX_Filter_t *filter;
+    AM_ErrorCode_t ret = AM_SUCCESS;
 
-	AM_TRY(dmx_get_openned_dev(dev_no, &dev));
-	pthread_mutex_lock(&dev->lock);
-	ret = dmx_get_used_filter(dev, fhandle, &filter);
-	if(ret==AM_SUCCESS)
-	{
-		dmx_wait_cb(dev);
-	
-		filter->cb = cb;
-		filter->user_data = data;
-	}
-	pthread_mutex_unlock(&dev->lock);
-	return ret;
+    AM_TRY(dmx_get_openned_dev(dev_no, &dev));
+    pthread_mutex_lock(&dev->lock);
+    ret = dmx_get_used_filter(dev, fhandle, &filter);
+    if (ret == AM_SUCCESS)
+    {
+        dmx_wait_cb(dev);
+
+        filter->cb = cb;
+        filter->user_data = data;
+    }
+    pthread_mutex_unlock(&dev->lock);
+    return ret;
 }
 
 /**\brief 设置解复用设备的输入源
@@ -827,31 +827,31 @@
  */
 AM_ErrorCode_t AM_DMX_SetInput(int dev_no, int input)
 {
-	AM_DMX_Device_t *dev;
-	AM_ErrorCode_t ret = AM_SUCCESS;
+    AM_DMX_Device_t *dev;
+    AM_ErrorCode_t ret = AM_SUCCESS;
 
-	AM_TRY(dmx_get_openned_dev(dev_no, &dev));
-	pthread_mutex_lock(&dev->lock);
-	if(!dev->drv->set_input)
-	{
-		printf("do not support set_input");
-		ret = AM_DMX_ERR_NOT_SUPPORTED;
-	}
+    AM_TRY(dmx_get_openned_dev(dev_no, &dev));
+    pthread_mutex_lock(&dev->lock);
+    if (!dev->drv->set_input)
+    {
+        printf("do not support set_input");
+        ret = AM_DMX_ERR_NOT_SUPPORTED;
+    }
 
-	if(ret==AM_SUCCESS)
-	{
-		ret = dev->drv->set_input(dev, input);
-	}
+    if (ret == AM_SUCCESS)
+    {
+        ret = dev->drv->set_input(dev, input);
+    }
 
-	pthread_mutex_unlock(&dev->lock);
-	if(ret==AM_SUCCESS)
-	{
-//		pthread_mutex_lock(&am_gAdpLock);
-		dev->src = input;
-//		pthread_mutex_unlock(&am_gAdpLock);
-	}
+    pthread_mutex_unlock(&dev->lock);
+    if (ret == AM_SUCCESS)
+    {
+//        pthread_mutex_lock(&am_gAdpLock);
+        dev->src = input;
+//        pthread_mutex_unlock(&am_gAdpLock);
+    }
 
-	return ret;
+    return ret;
 }
 
 /**\brief DMX同步,可用于等待回调函数执行完毕
@@ -862,23 +862,23 @@
  */
 AM_ErrorCode_t AM_DMX_Sync(int dev_no)
 {
-	AM_DMX_Device_t *dev;
-	AM_ErrorCode_t ret = AM_SUCCESS;
+    AM_DMX_Device_t *dev;
+    AM_ErrorCode_t ret = AM_SUCCESS;
 
-	AM_TRY(dmx_get_openned_dev(dev_no, &dev));
-	pthread_mutex_lock(&dev->lock);
-	if(dev->thread!=pthread_self())
-	{
-		while(dev->flags&DMX_FL_RUN_CB)
-			pthread_cond_wait(&dev->cond, &dev->lock);
-	}
-	pthread_mutex_unlock(&dev->lock);
-	return ret;
+    AM_TRY(dmx_get_openned_dev(dev_no, &dev));
+    pthread_mutex_lock(&dev->lock);
+    if (dev->thread != pthread_self())
+    {
+        while (dev->flags & DMX_FL_RUN_CB)
+            pthread_cond_wait(&dev->cond, &dev->lock);
+    }
+    pthread_mutex_unlock(&dev->lock);
+    return ret;
 }
 
 AM_ErrorCode_t AM_DMX_GetScrambleStatus(int dev_no, AM_Bool_t dev_status[2])
 {
-	return AM_SUCCESS;
+    return AM_SUCCESS;
 }
 
 
diff --git a/test/am_ca_test/am_dmx.h b/test/am_ca_test/am_dmx.h
index d337343..4a4605a 100644
--- a/test/am_ca_test/am_dmx.h
+++ b/test/am_ca_test/am_dmx.h
@@ -46,20 +46,20 @@
 /**\brief Error code of the demux module*/
 enum AM_DMX_ErrorCode
 {
-	AM_DMX_ERROR_BASE=AM_ERROR_BASE(AM_MOD_DMX),
-	AM_DMX_ERR_INVALID_DEV_NO,          /**< Invalid device number*/
-	AM_DMX_ERR_INVALID_ID,              /**< Invalid filer handle*/
-	AM_DMX_ERR_BUSY,                    /**< The device has already been openned*/
-	AM_DMX_ERR_NOT_ALLOCATED,           /**< The device has not been allocated*/
-	AM_DMX_ERR_CANNOT_CREATE_THREAD,    /**< Cannot create new thread*/
-	AM_DMX_ERR_CANNOT_OPEN_DEV,         /**< Cannot open device*/
-	AM_DMX_ERR_NOT_SUPPORTED,           /**< Not supported*/
-	AM_DMX_ERR_NO_FREE_FILTER,          /**< No free filter*/
-	AM_DMX_ERR_NO_MEM,                  /**< Not enough memory*/
-	AM_DMX_ERR_TIMEOUT,                 /**< Timeout*/
-	AM_DMX_ERR_SYS,                     /**< System error*/
-	AM_DMX_ERR_NO_DATA,                 /**< No data received*/
-	AM_DMX_ERR_END
+    AM_DMX_ERROR_BASE=AM_ERROR_BASE(AM_MOD_DMX),
+    AM_DMX_ERR_INVALID_DEV_NO,          /**< Invalid device number*/
+    AM_DMX_ERR_INVALID_ID,              /**< Invalid filer handle*/
+    AM_DMX_ERR_BUSY,                    /**< The device has already been openned*/
+    AM_DMX_ERR_NOT_ALLOCATED,           /**< The device has not been allocated*/
+    AM_DMX_ERR_CANNOT_CREATE_THREAD,    /**< Cannot create new thread*/
+    AM_DMX_ERR_CANNOT_OPEN_DEV,         /**< Cannot open device*/
+    AM_DMX_ERR_NOT_SUPPORTED,           /**< Not supported*/
+    AM_DMX_ERR_NO_FREE_FILTER,          /**< No free filter*/
+    AM_DMX_ERR_NO_MEM,                  /**< Not enough memory*/
+    AM_DMX_ERR_TIMEOUT,                 /**< Timeout*/
+    AM_DMX_ERR_SYS,                     /**< System error*/
+    AM_DMX_ERR_NO_DATA,                 /**< No data received*/
+    AM_DMX_ERR_END
 };
 
 /****************************************************************************
@@ -69,20 +69,20 @@
 /**\brief Input source of the demux*/
 typedef enum
 {
-	AM_DMX_SRC_TS0,                    /**< TS input port 0*/
-	AM_DMX_SRC_TS1,                    /**< TS input port 1*/
-	AM_DMX_SRC_TS2,                    /**< TS input port 2*/
-	AM_DMX_SRC_TS3,                    /**< TS input port 3*/
-	AM_DMX_SRC_HIU,                     /**< HIU input (memory)*/
-	AM_DMX_SRC_HIU1
+    AM_DMX_SRC_TS0,                    /**< TS input port 0*/
+    AM_DMX_SRC_TS1,                    /**< TS input port 1*/
+    AM_DMX_SRC_TS2,                    /**< TS input port 2*/
+    AM_DMX_SRC_TS3,                    /**< TS input port 3*/
+    AM_DMX_SRC_HIU,                     /**< HIU input (memory)*/
+    AM_DMX_SRC_HIU1
 } AM_DMX_Source_t;
 
 /**\brief Demux device open parameters*/
 typedef struct
 {
-	AM_Bool_t use_sw_filter;           /**< M_TURE to use DVR software filters.*/
-	int       dvr_fifo_no;             /**< Async fifo number if use software filters.*/
-	int       dvr_buf_size;            /**< Async fifo buffer size if use software filters.*/
+    AM_Bool_t use_sw_filter;           /**< M_TURE to use DVR software filters.*/
+    int       dvr_fifo_no;             /**< Async fifo number if use software filters.*/
+    int       dvr_buf_size;            /**< Async fifo buffer size if use software filters.*/
 } AM_DMX_OpenPara_t;
 
 /**\brief Filter received data callback function
diff --git a/test/am_ca_test/am_dmx_internal.h b/test/am_ca_test/am_dmx_internal.h
index 9662a3c..a2883e7 100644
--- a/test/am_ca_test/am_dmx_internal.h
+++ b/test/am_ca_test/am_dmx_internal.h
@@ -54,45 +54,45 @@
 /**\brief 解复用设备驱动*/
 typedef struct
 {
-	AM_ErrorCode_t (*open)(AM_DMX_Device_t *dev, const AM_DMX_OpenPara_t *para);
-	AM_ErrorCode_t (*close)(AM_DMX_Device_t *dev);
-	AM_ErrorCode_t (*alloc_filter)(AM_DMX_Device_t *dev, AM_DMX_Filter_t *filter);
-	AM_ErrorCode_t (*free_filter)(AM_DMX_Device_t *dev, AM_DMX_Filter_t *filter);
-	AM_ErrorCode_t (*set_sec_filter)(AM_DMX_Device_t *dev, AM_DMX_Filter_t *filter, const struct dmx_sct_filter_params *params);
-	AM_ErrorCode_t (*set_pes_filter)(AM_DMX_Device_t *dev, AM_DMX_Filter_t *filter, const struct dmx_pes_filter_params *params);
-	AM_ErrorCode_t (*enable_filter)(AM_DMX_Device_t *dev, AM_DMX_Filter_t *filter, AM_Bool_t enable);
-	AM_ErrorCode_t (*set_buf_size)(AM_DMX_Device_t *dev, AM_DMX_Filter_t *filter, int size);
-	AM_ErrorCode_t (*poll)(AM_DMX_Device_t *dev, AM_DMX_FilterMask_t *mask, int timeout);
-	AM_ErrorCode_t (*read)(AM_DMX_Device_t *dev, AM_DMX_Filter_t *filter, uint8_t *buf, int *size);
-	AM_ErrorCode_t (*set_input)(AM_DMX_Device_t *dev, int input);
-	AM_ErrorCode_t (*get_stc)(AM_DMX_Device_t *dev, AM_DMX_Filter_t *filter);
+    AM_ErrorCode_t (*open)(AM_DMX_Device_t *dev, const AM_DMX_OpenPara_t *para);
+    AM_ErrorCode_t (*close)(AM_DMX_Device_t *dev);
+    AM_ErrorCode_t (*alloc_filter)(AM_DMX_Device_t *dev, AM_DMX_Filter_t *filter);
+    AM_ErrorCode_t (*free_filter)(AM_DMX_Device_t *dev, AM_DMX_Filter_t *filter);
+    AM_ErrorCode_t (*set_sec_filter)(AM_DMX_Device_t *dev, AM_DMX_Filter_t *filter, const struct dmx_sct_filter_params *params);
+    AM_ErrorCode_t (*set_pes_filter)(AM_DMX_Device_t *dev, AM_DMX_Filter_t *filter, const struct dmx_pes_filter_params *params);
+    AM_ErrorCode_t (*enable_filter)(AM_DMX_Device_t *dev, AM_DMX_Filter_t *filter, AM_Bool_t enable);
+    AM_ErrorCode_t (*set_buf_size)(AM_DMX_Device_t *dev, AM_DMX_Filter_t *filter, int size);
+    AM_ErrorCode_t (*poll)(AM_DMX_Device_t *dev, AM_DMX_FilterMask_t *mask, int timeout);
+    AM_ErrorCode_t (*read)(AM_DMX_Device_t *dev, AM_DMX_Filter_t *filter, uint8_t *buf, int *size);
+    AM_ErrorCode_t (*set_input)(AM_DMX_Device_t *dev, int input);
+    AM_ErrorCode_t (*get_stc)(AM_DMX_Device_t *dev, AM_DMX_Filter_t *filter);
 } AM_DMX_Driver_t;
 
 /**\brief Section过滤器*/
 struct AM_DMX_Filter
 {
-	void      *drv_data; /**< 驱动私有数据*/
-	AM_Bool_t  used;     /**< 此Filter是否已经分配*/
-	AM_Bool_t  enable;   /**< 此Filter设备是否使能*/
-	int        id;       /**< Filter ID*/
-	AM_DMX_DataCb       cb;        /**< 解复用数据回调函数*/
-	void               *user_data; /**< 数据回调函数用户参数*/
+    void      *drv_data; /**< 驱动私有数据*/
+    AM_Bool_t  used;     /**< 此Filter是否已经分配*/
+    AM_Bool_t  enable;   /**< 此Filter设备是否使能*/
+    int        id;       /**< Filter ID*/
+    AM_DMX_DataCb       cb;        /**< 解复用数据回调函数*/
+    void               *user_data; /**< 数据回调函数用户参数*/
 };
 
 /**\brief 解复用设备*/
 struct AM_DMX_Device
 {
-	int                 dev_no;  /**< 设备号*/
-	const AM_DMX_Driver_t *drv;  /**< 设备驱动*/
-	void               *drv_data;/**< 驱动私有数据*/
-	AM_DMX_Filter_t     filters[DMX_FILTER_COUNT];   /**< 设备中的Filter*/
-	int                 open_count; /**< 设备已经打开次数*/
-	AM_Bool_t           enable_thread; /**< 数据线程已经运行*/
-	int                 flags;   /**< 线程运行状态控制标志*/
-	pthread_t           thread;  /**< 数据检测线程*/
-	pthread_mutex_t     lock;    /**< 设备保护互斥体*/
-	pthread_cond_t      cond;    /**< 条件变量*/
-	AM_DMX_Source_t     src;     /**< TS输入源*/
+    int                 dev_no;  /**< 设备号*/
+    const AM_DMX_Driver_t *drv;  /**< 设备驱动*/
+    void               *drv_data;/**< 驱动私有数据*/
+    AM_DMX_Filter_t     filters[DMX_FILTER_COUNT];   /**< 设备中的Filter*/
+    int                 open_count; /**< 设备已经打开次数*/
+    AM_Bool_t           enable_thread; /**< 数据线程已经运行*/
+    int                 flags;   /**< 线程运行状态控制标志*/
+    pthread_t           thread;  /**< 数据检测线程*/
+    pthread_mutex_t     lock;    /**< 设备保护互斥体*/
+    pthread_cond_t      cond;    /**< 条件变量*/
+    AM_DMX_Source_t     src;     /**< TS输入源*/
 };
 
 
diff --git a/test/am_ca_test/am_inject.c b/test/am_ca_test/am_inject.c
index 9b620f4..b4366e7 100644
--- a/test/am_ca_test/am_inject.c
+++ b/test/am_ca_test/am_inject.c
@@ -52,177 +52,177 @@
 
 typedef struct
 {
-	int id;
-	int ofd;
-	pthread_t thread;
-	int running;
-	int fd;
+    int id;
+    int ofd;
+    pthread_t thread;
+    int running;
+    int fd;
 }DVRData;
 
 static DVRData data_threads[DVR_DEV_COUNT];
 
 static int dvr_data_write(int fd, uint8_t *buf, int size)
 {
-	int ret;
-	int left = size;
-	uint8_t *p = buf;
+    int ret;
+    int left = size;
+    uint8_t *p = buf;
 
-	while (left > 0)
-	{
-		printf("write start\n");
-		ret = write(fd, p, left);
-		printf("write end\n");
-		if (ret == -1)
-		{
-			if (errno != EINTR)
-			{
-				printf("Write DVR data failed: %s", strerror(errno));
-				break;
-			}
-			ret = 0;
-		} else {
-			printf("%s write cnt:%d\n",__FUNCTION__,ret);
-		}
+    while (left > 0)
+    {
+        printf("write start\n");
+        ret = write(fd, p, left);
+        printf("write end\n");
+        if (ret == -1)
+        {
+            if (errno != EINTR)
+            {
+                printf("Write DVR data failed: %s", strerror(errno));
+                break;
+            }
+            ret = 0;
+        } else {
+            printf("%s write cnt:%d\n",__FUNCTION__,ret);
+        }
 
-		left -= ret;
-		p += ret;
-	}
+        left -= ret;
+        p += ret;
+    }
 
-	return (size - left);
+    return (size - left);
 }
 
 static void handle_signal(int signal)
 {
-	UNUSED(signal);
+    UNUSED(signal);
 
-	exit(0);
+    exit(0);
 }
 
 static void init_signal_handler()
 {
-	struct sigaction act;
-	act.sa_handler = handle_signal;
-	sigaction(SIGINT, &act, NULL);
+    struct sigaction act;
+    act.sa_handler = handle_signal;
+    sigaction(SIGINT, &act, NULL);
 }
 
 static int inject_running=0;
 static int inject_loop=0;
 static void* inject_entry(void *arg)
 {
-	DVRData *dvr_data = (DVRData *)arg;
-	int sock = dvr_data->ofd;
-	int fd = dvr_data->fd;
-	uint8_t buf[188*100];
-	int len, left=0, send, ret;
-	int cnt=50;
-	struct timeval start_tv;
-	struct timeval now_tv;
-	unsigned int diff_time = 0;
-	unsigned int total_len = 0;
+    DVRData *dvr_data = (DVRData *)arg;
+    int sock = dvr_data->ofd;
+    int fd = dvr_data->fd;
+    uint8_t buf[188*100];
+    int len, left=0, send, ret;
+    int cnt=50;
+    struct timeval start_tv;
+    struct timeval now_tv;
+    unsigned int diff_time = 0;
+    unsigned int total_len = 0;
 
-	gettimeofday(&start_tv, NULL);
-	printf("inject thread start");
-	while (inject_running) {
-		len = sizeof(buf) - left;
-		ret = read(sock, buf+left, len);
-		if (ret > 0) {
-			printf("recv %d bytes\n", ret);
-/*			if (!cnt){
-				cnt=50;
-				printf("recv %d\n", ret);
-			}
-			cnt--; */
-			left += ret;
-			total_len += ret;
-		} else {
-			if (inject_loop && ((ret == 0) || (errno == EAGAIN))) {
-				printf("loop\n");
-				lseek(sock, 0, SEEK_SET);
-				left=0;
-				continue;
-			} else {
-				fprintf(stderr, "read file failed [%d:%s] ret=%d left=%d\n", errno, strerror(errno), ret, left);
-				break;
-			}
-		}
-		if (left) {
-			gettimeofday(&now_tv, NULL);
-			if (now_tv.tv_usec < start_tv.tv_usec) {
-				diff_time = (now_tv.tv_sec - 1 - start_tv.tv_sec) * 1000 + (now_tv.tv_usec + 1*1000*1000 - start_tv.tv_usec) / 1000;
-			} else {
-				diff_time = (now_tv.tv_sec - start_tv.tv_sec) * 1000 + (now_tv.tv_usec - start_tv.tv_usec) / 1000;
-			}
+    gettimeofday(&start_tv, NULL);
+    printf("inject thread start");
+    while (inject_running) {
+        len = sizeof(buf) - left;
+        ret = read(sock, buf+left, len);
+        if (ret > 0) {
+            printf("recv %d bytes\n", ret);
+/*            if (!cnt){
+                cnt=50;
+                printf("recv %d\n", ret);
+            }
+            cnt--; */
+            left += ret;
+            total_len += ret;
+        } else {
+            if (inject_loop && ((ret == 0) || (errno == EAGAIN))) {
+                printf("loop\n");
+                lseek(sock, 0, SEEK_SET);
+                left=0;
+                continue;
+            } else {
+                fprintf(stderr, "read file failed [%d:%s] ret=%d left=%d\n", errno, strerror(errno), ret, left);
+                break;
+            }
+        }
+        if (left) {
+            gettimeofday(&now_tv, NULL);
+            if (now_tv.tv_usec < start_tv.tv_usec) {
+                diff_time = (now_tv.tv_sec - 1 - start_tv.tv_sec) * 1000 + (now_tv.tv_usec + 1*1000*1000 - start_tv.tv_usec) / 1000;
+            } else {
+                diff_time = (now_tv.tv_sec - start_tv.tv_sec) * 1000 + (now_tv.tv_usec - start_tv.tv_usec) / 1000;
+            }
 
-			if ( diff_time != 0 && total_len/1024/1024*8*1000/diff_time > 4) {
-				usleep(20*1000);
-			}
+            if ( diff_time != 0 && total_len/1024/1024*8*1000/diff_time > 4) {
+                usleep(20*1000);
+            }
 
-			send = left;
-			send = dvr_data_write(fd, buf, send);
-			printf("write %d bytes\n", send);
-			if (send) {
-				left -= send;
-				if (left)
-					memmove(buf, buf+send, left);
-				//AM_DEBUG(1, "inject %d bytes", send);
-			}
-		}
-	}
-	printf("inject thread end");
-	inject_running = -1;
-	return NULL;
+            send = left;
+            send = dvr_data_write(fd, buf, send);
+            printf("write %d bytes\n", send);
+            if (send) {
+                left -= send;
+                if (left)
+                    memmove(buf, buf+send, left);
+                //AM_DEBUG(1, "inject %d bytes", send);
+            }
+        }
+    }
+    printf("inject thread end");
+    inject_running = -1;
+    return NULL;
 }
 
 int inject_file(int dvr_no, char *inject_name)
 {
-	int loop = 0;
-	int ofd;
-	char dev_name[32];
-	int fd;
-	int ret;
-	pthread_t th;
+    int loop = 0;
+    int ofd;
+    char dev_name[32];
+    int fd;
+    int ret;
+    pthread_t th;
 
-	printf("inject file name=%s to dvr%d\n", inject_name, dvr_no);
+    printf("inject file name=%s to dvr%d\n", inject_name, dvr_no);
 
-	init_signal_handler();
-	snprintf(dev_name, sizeof(dev_name), "/dev/dvb0.dvr%d", dvr_no);
+    init_signal_handler();
+    snprintf(dev_name, sizeof(dev_name), "/dev/dvb0.dvr%d", dvr_no);
 
-	fd = open(dev_name, O_WRONLY);
-	if (fd == -1)
-	{
-		printf("cannot open \"%s\" (%s)", dev_name, strerror(errno));
-		return -1;
-	}
-//	fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK, 0);
+    fd = open(dev_name, O_WRONLY);
+    if (fd == -1)
+    {
+        printf("cannot open \"%s\" (%s)", dev_name, strerror(errno));
+        return -1;
+    }
+//    fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK, 0);
 
-	ret = ioctl(fd, DMX_SET_INPUT, INPUT_LOCAL);
-	printf("DMX_SET_INPUT ret:%d, %s\n", ret, strerror(errno));
+    ret = ioctl(fd, DMX_SET_INPUT, INPUT_LOCAL);
+    printf("DMX_SET_INPUT ret:%d, %s\n", ret, strerror(errno));
 
-	data_threads[0].id =0;
-	data_threads[0].fd = fd;
-	data_threads[0].running = 0;
+    data_threads[0].id =0;
+    data_threads[0].fd = fd;
+    data_threads[0].running = 0;
 
-	ofd = open(inject_name, O_RDWR, S_IRUSR);
-	if (ofd == -1) {
-		printf("cannot open \"%s\" (%s)", inject_name, strerror(errno));
-		return -1;
-	}
-	data_threads[0].ofd = ofd;
+    ofd = open(inject_name, O_RDWR, S_IRUSR);
+    if (ofd == -1) {
+        printf("cannot open \"%s\" (%s)", inject_name, strerror(errno));
+        return -1;
+    }
+    data_threads[0].ofd = ofd;
 
-	inject_loop = loop;
-	inject_running = 1;
-	pthread_create(&th, NULL, inject_entry, (void*)(long)&data_threads[0]);
+    inject_loop = loop;
+    inject_running = 1;
+    pthread_create(&th, NULL, inject_entry, (void*)(long)&data_threads[0]);
 
-	return 0;
+    return 0;
 }
 int inject_file_and_rec_close(void) {
 
-	inject_running = 0;
+    inject_running = 0;
 
-	do {}while((inject_running != -1));
+    do {}while((inject_running != -1));
 
-	close(data_threads[0].fd);
-	close(data_threads[0].ofd);
-	return 0;
+    close(data_threads[0].fd);
+    close(data_threads[0].ofd);
+    return 0;
 }
 
diff --git a/test/am_ca_test/am_key.c b/test/am_ca_test/am_key.c
index 48622ba..b1039ed 100644
--- a/test/am_ca_test/am_key.c
+++ b/test/am_ca_test/am_key.c
@@ -42,120 +42,120 @@
 static int s_fd = -1;
 int key_open (void)
 {
-	char buf[32];
+    char buf[32];
 
-	if (s_fd != -1)
-		return s_fd;
+    if (s_fd != -1)
+        return s_fd;
 
-	snprintf(buf, sizeof(buf), "/dev/key");
-	s_fd = open(buf, O_RDWR);
-	if(s_fd == -1)
-	{
-		printf("cannot open \"%s\" (%d:%s)", DEV_NAME, errno, strerror(errno));
-		return -1;
-	}
-	printf("%s key fd:%d\n", buf, s_fd);
-	return s_fd;
+    snprintf(buf, sizeof(buf), "/dev/key");
+    s_fd = open(buf, O_RDWR);
+    if (s_fd == -1)
+    {
+        printf("cannot open \"%s\" (%d:%s)", DEV_NAME, errno, strerror(errno));
+        return -1;
+    }
+    printf("%s key fd:%d\n", buf, s_fd);
+    return s_fd;
 }
 
 int key_close(int fd)
 {
-	if (fd == -1) {
-		printf("key_close inavlid fd\n");
-		return 0;
-	}
-	close(fd);
-	s_fd = -1;
-	return 0;
+    if (fd == -1) {
+        printf("key_close invalid fd\n");
+        return 0;
+    }
+    close(fd);
+    s_fd = -1;
+    return 0;
 }
 int key_alloc(int fd, int is_iv)
 {
-	int ret = 0;
-	struct key_alloc param;
+    int ret = 0;
+    struct key_alloc param;
 
-	if (fd == -1) {
-		printf("key alloc fd invalid\n");
-		return -1;
-	}
-	param.is_iv = is_iv;
-	param.key_index  = -1;
+    if (fd == -1) {
+        printf("key alloc fd invalid\n");
+        return -1;
+    }
+    param.is_iv = is_iv;
+    param.key_index  = -1;
 
-	ret = ioctl(fd, KEY_ALLOC, &param);
-	if (ret == 0) {
-		printf("key_alloc index:%d\n", param.key_index);
-		return param.key_index;
-	} else {
-		printf("key_alloc key fail,fd:%d, is_iv:%d\n", fd, is_iv);
-		printf("fail \"%s\" (%d:%s)", DEV_NAME, errno, strerror(errno));
-		return -1;
-	}
+    ret = ioctl(fd, KEY_ALLOC, &param);
+    if (ret == 0) {
+        printf("key_alloc index:%d\n", param.key_index);
+        return param.key_index;
+    } else {
+        printf("key_alloc key fail,fd:%d, is_iv:%d\n", fd, is_iv);
+        printf("fail \"%s\" (%d:%s)", DEV_NAME, errno, strerror(errno));
+        return -1;
+    }
 }
 
 int key_config(int fd, int key_index, int key_userid, int key_algo, unsigned int ext_value)
 {
-	int ret = 0;
-	struct key_config config;
+    int ret = 0;
+    struct key_config config;
 
-	if (fd == -1) {
-		printf("key config fd invalid\n");
-		return -1;
-	}
-	config.key_userid = key_userid;
-	config.key_algo   = key_algo;
-	config.key_index  = key_index;
-	config.ext_value  = ext_value;
+    if (fd == -1) {
+        printf("key config fd invalid\n");
+        return -1;
+    }
+    config.key_userid = key_userid;
+    config.key_algo   = key_algo;
+    config.key_index  = key_index;
+    config.ext_value  = ext_value;
 
-	ret = ioctl(fd, KEY_CONFIG, &config);
-	if (ret == 0) {
-		printf("key_config index:%d\n", config.key_index);
-		return config.key_index;
-	} else {
-		printf("key_config key fail,fd:%d, key_userid:%d, key_algo:%d\n", fd, key_userid, key_algo);
-		printf("fail \"%s\" (%d:%s)", DEV_NAME, errno, strerror(errno));
-		return -1;
-	}
+    ret = ioctl(fd, KEY_CONFIG, &config);
+    if (ret == 0) {
+        printf("key_config index:%d\n", config.key_index);
+        return config.key_index;
+    } else {
+        printf("key_config key fail,fd:%d, key_userid:%d, key_algo:%d\n", fd, key_userid, key_algo);
+        printf("fail \"%s\" (%d:%s)", DEV_NAME, errno, strerror(errno));
+        return -1;
+    }
 }
 int key_free(int fd, int key_index)
 {
-	int ret = 0;
+    int ret = 0;
 
-	printf("key_free fd:%d key_index:%d\n", fd, key_index);
-	if (fd == -1 || key_index == -1) {
-		printf("key_free invalid parameter, fd:%d, key_index:%d\n", fd, key_index);
-		return -1;
-	}
+    printf("key_free fd:%d key_index:%d\n", fd, key_index);
+    if (fd == -1 || key_index == -1) {
+        printf("key_free invalid parameter, fd:%d, key_index:%d\n", fd, key_index);
+        return -1;
+    }
 
-	ret = ioctl(fd, KEY_FREE, key_index);
-	if (ret == 0) {
-		printf("key_free key_index:%d succees\n", key_index);
-		return 0;
-	} else {
-		printf("key_free key_index:%d fail\n", key_index);
-		return -1;
-	}
+    ret = ioctl(fd, KEY_FREE, key_index);
+    if (ret == 0) {
+        printf("key_free key_index:%d success\n", key_index);
+        return 0;
+    } else {
+        printf("key_free key_index:%d fail\n", key_index);
+        return -1;
+    }
 }
 
 int key_set(int fd, int key_index, char *key, int key_len)
 {
-	int ret = 0;
-	struct key_descr key_d;
+    int ret = 0;
+    struct key_descr key_d;
 
-	if (fd == -1 || key_index ==  -1 || key_len > 32) {
-		printf("key_set invalid parameter, fd:%d, key_index:%d, key_len:%d\n",
-			fd, key_index, key_len);
-		return -1;
-	}
+    if (fd == -1 || key_index ==  -1 || key_len > 32) {
+        printf("key_set invalid parameter, fd:%d, key_index:%d, key_len:%d\n",
+            fd, key_index, key_len);
+        return -1;
+    }
 
-	key_d.key_index = key_index;
-	memcpy(&key_d.key, key, key_len);
-	key_d.key_len = key_len;
-	ret = ioctl(fd, KEY_SET, &key_d);
-	if (ret == 0) {
-		printf("key_set success\n");
-		return 0;
-	} else {
-		printf("key_set fail\n");
-		return -1;
-	}
+    key_d.key_index = key_index;
+    memcpy(&key_d.key, key, key_len);
+    key_d.key_len = key_len;
+    ret = ioctl(fd, KEY_SET, &key_d);
+    if (ret == 0) {
+        printf("key_set success\n");
+        return 0;
+    } else {
+        printf("key_set fail\n");
+        return -1;
+    }
 }
 
diff --git a/test/am_ca_test/am_mem.h b/test/am_ca_test/am_mem.h
index 8182b71..fd05a0d 100644
--- a/test/am_ca_test/am_mem.h
+++ b/test/am_ca_test/am_mem.h
@@ -37,47 +37,47 @@
 
 /**\brief 内存缓冲区分配*/
 #define AM_MEM_Alloc(_size) \
-	({\
-	void *_ptr = malloc(_size);\
-	if (!_ptr) {\
-		AM_MEM_ERROR_DEBUG(_size);\
-	}\
-	_ptr;\
-	})
+    ({\
+    void *_ptr = malloc(_size);\
+    if (!_ptr) {\
+        AM_MEM_ERROR_DEBUG(_size);\
+    }\
+    _ptr;\
+    })
 
 /**\brief 重新设定缓冲区大小*/
 #define AM_MEM_Realloc(_old,_size) \
-	({\
-	void *_ptr=realloc(_old,_size);\
-	if (!_ptr) {\
-		AM_MEM_ERROR_DEBUG(_size);\
-	}\
-	_ptr;\
-	})
+    ({\
+    void *_ptr=realloc(_old,_size);\
+    if (!_ptr) {\
+        AM_MEM_ERROR_DEBUG(_size);\
+    }\
+    _ptr;\
+    })
 
 /**\brief 内存缓冲区释放*/
 #define AM_MEM_Free(_ptr) \
-	AM_MACRO_BEGIN\
-	if (_ptr) free(_ptr);\
-	AM_MACRO_END
+    AM_MACRO_BEGIN\
+    if (_ptr) free(_ptr);\
+    AM_MACRO_END
 
 /**\brief 分配内存并复制字符串*/
 #define AM_MEM_Strdup(_str) \
-	({\
-	void *_ptr = strdup(_str);\
-	if (!_ptr) {\
-		AM_MEM_ERROR_DEBUG(strlen(_str));\
-	}\
-	_ptr;\
-	})
+    ({\
+    void *_ptr = strdup(_str);\
+    if (!_ptr) {\
+        AM_MEM_ERROR_DEBUG(strlen(_str));\
+    }\
+    _ptr;\
+    })
 
 /**\brief 分配内存并将缓冲区清0*/
 #define AM_MEM_Alloc0(_size) \
-	({\
-	void *_ptr = AM_MEM_Alloc((_size));\
-	if(_ptr) memset(_ptr, 0, (_size));\
-	_ptr;\
-	})
+    ({\
+    void *_ptr = AM_MEM_Alloc((_size));\
+    if(_ptr) memset(_ptr, 0, (_size));\
+    _ptr;\
+    })
 
 /**\brief 根据类型_type的大小分配内存*/
 #define AM_MEM_ALLOC_TYPE(_type)       AM_MEM_Alloc(sizeof(_type))
@@ -93,11 +93,11 @@
 
 /**\brief 从内存池分配一个缓冲区并清0*/
 #define AM_MEM_PoolAlloc0(_pool,_size) \
-	({\
-	void *_ptr = AM_MEM_PoolAlloc(_pool,_size);\
-	if(_ptr) memset(_ptr, 0, _size);\
-	_ptr;\
-	})
+    ({\
+    void *_ptr = AM_MEM_PoolAlloc(_pool,_size);\
+    if(_ptr) memset(_ptr, 0, _size);\
+    _ptr;\
+    })
 
 /**\brief 根据类型_type的大小从内存池分配内存*/
 #define AM_MEM_POOL_ALLOC_TYPE(_pool,_type)       AM_MEM_PoolAlloc(_pool,sizeof(_type))
@@ -121,8 +121,8 @@
  */
 typedef struct
 {
-	int        pool_size;   /**< 每次分配的内存大小*/
-	void      *pools;       /**< 内存块链表*/
+    int        pool_size;   /**< 每次分配的内存大小*/
+    void      *pools;       /**< 内存块链表*/
 } AM_MEM_Pool_t;
 
 /****************************************************************************
diff --git a/test/am_ca_test/am_types.h b/test/am_ca_test/am_types.h
index f6c44e6..3b14de5 100644
--- a/test/am_ca_test/am_types.h
+++ b/test/am_ca_test/am_types.h
@@ -41,44 +41,44 @@
 /**\brief The module's index */
 enum AM_MOD_ID
 {
-	AM_MOD_EVT,    /**< Event module*/
-	AM_MOD_DMX,    /**< Demux module*/
-	AM_MOD_DVR,    /**< DVR module*/
-	AM_MOD_NET,    /**< Network manager module*/
-	AM_MOD_OSD,    /**< OSD module*/
-	AM_MOD_AV,     /**< AV decoder module*/
-	AM_MOD_AOUT,   /**< Audio output device module*/
-	AM_MOD_VOUT,   /**< Video output device module*/
-	AM_MOD_SMC,    /**< Smartcard module*/
-	AM_MOD_INP,    /**< Input device module*/
-	AM_MOD_FEND,   /**< DVB frontend device module*/
-	AM_MOD_DSC,    /**< Descrambler device module*/
-	AM_MOD_CFG,    /**< Configure file manager module*/
-	AM_MOD_SI,     /**< SI decoder module*/
-	AM_MOD_SCAN,   /**< Channel scanner module*/
-	AM_MOD_EPG,    /**< EPG scanner module*/
-	AM_MOD_IMG,    /**< Image loader module*/
-	AM_MOD_FONT,   /**< Font manager module*/
-	AM_MOD_DB,     /**< Database module*/
-	AM_MOD_GUI,    /**< GUI module*/
-	AM_MOD_REC,    /**< Recorder module*/
-	AM_MOD_TV,     /**< TV manager module*/
-	AM_MOD_SUB,    /**< Subtitle module*/
-	AM_MOD_SUB2,   /**< Subtitle(version 2) module*/
-	AM_MOD_TT,     /**< Teletext module*/
-	AM_MOD_TT2,    /**< Teletext(version 2) module*/
-	AM_MOD_FEND_DISEQCCMD,/**< Diseqc command module*/
-	AM_MOD_FENDCTRL, /**< DVB frontend high level control module*/
-	AM_MOD_PES,    /**< PES parser module*/
-	AM_MOD_CAMAN,  /**< CA manager module*/
-	AM_MOD_CI,     /**< DVB-CI module*/
-	AM_MOD_USERDATA, /**< MPEG user data reader device module*/
-	AM_MOD_CC,     /**< Close caption module*/
-	AM_MOD_AD,     /**< Audio description module*/
-	AM_MOD_UPD,    /**< Uploader module*/
-	AM_MOD_TFILE, /*File wrapper module*/
-	AM_MOD_SCTE27,
-	AM_MOD_MAX
+    AM_MOD_EVT,    /**< Event module*/
+    AM_MOD_DMX,    /**< Demux module*/
+    AM_MOD_DVR,    /**< DVR module*/
+    AM_MOD_NET,    /**< Network manager module*/
+    AM_MOD_OSD,    /**< OSD module*/
+    AM_MOD_AV,     /**< AV decoder module*/
+    AM_MOD_AOUT,   /**< Audio output device module*/
+    AM_MOD_VOUT,   /**< Video output device module*/
+    AM_MOD_SMC,    /**< Smartcard module*/
+    AM_MOD_INP,    /**< Input device module*/
+    AM_MOD_FEND,   /**< DVB frontend device module*/
+    AM_MOD_DSC,    /**< Descrambler device module*/
+    AM_MOD_CFG,    /**< Configure file manager module*/
+    AM_MOD_SI,     /**< SI decoder module*/
+    AM_MOD_SCAN,   /**< Channel scanner module*/
+    AM_MOD_EPG,    /**< EPG scanner module*/
+    AM_MOD_IMG,    /**< Image loader module*/
+    AM_MOD_FONT,   /**< Font manager module*/
+    AM_MOD_DB,     /**< Database module*/
+    AM_MOD_GUI,    /**< GUI module*/
+    AM_MOD_REC,    /**< Recorder module*/
+    AM_MOD_TV,     /**< TV manager module*/
+    AM_MOD_SUB,    /**< Subtitle module*/
+    AM_MOD_SUB2,   /**< Subtitle(version 2) module*/
+    AM_MOD_TT,     /**< Teletext module*/
+    AM_MOD_TT2,    /**< Teletext(version 2) module*/
+    AM_MOD_FEND_DISEQCCMD,/**< Diseqc command module*/
+    AM_MOD_FENDCTRL, /**< DVB frontend high level control module*/
+    AM_MOD_PES,    /**< PES parser module*/
+    AM_MOD_CAMAN,  /**< CA manager module*/
+    AM_MOD_CI,     /**< DVB-CI module*/
+    AM_MOD_USERDATA, /**< MPEG user data reader device module*/
+    AM_MOD_CC,     /**< Close caption module*/
+    AM_MOD_AD,     /**< Audio description module*/
+    AM_MOD_UPD,    /**< Uploader module*/
+    AM_MOD_TFILE, /*File wrapper module*/
+    AM_MOD_SCTE27,
+    AM_MOD_MAX
 };
 
 /**\brief Get the error code base of each module
diff --git a/test/am_ca_test/am_util.h b/test/am_ca_test/am_util.h
index c80ea27..d89351f 100644
--- a/test/am_ca_test/am_util.h
+++ b/test/am_ca_test/am_util.h
@@ -62,54 +62,54 @@
 
 /**\brief 检查如果返回值是否错误,返回错误代码给调用函数*/
 #define AM_TRY(_func) \
-	AM_MACRO_BEGIN\
-	AM_ErrorCode_t _ret;\
-	if ((_ret=(_func))!=AM_SUCCESS)\
-		return _ret;\
-	AM_MACRO_END
+    AM_MACRO_BEGIN\
+    AM_ErrorCode_t _ret;\
+    if ((_ret=(_func))!=AM_SUCCESS)\
+        return _ret;\
+    AM_MACRO_END
 
 /**\brief 检查返回值是否错误,如果错误,跳转到final标号。注意:函数中必须定义"AM_ErrorCode_t ret"和标号"final"*/
 #define AM_TRY_FINAL(_func)\
-	AM_MACRO_BEGIN\
-	if ((ret=(_func))!=AM_SUCCESS)\
-		goto final;\
-	AM_MACRO_END
+    AM_MACRO_BEGIN\
+    if ((ret=(_func))!=AM_SUCCESS)\
+        goto final;\
+    AM_MACRO_END
 
 /**\brief 开始解析一个被指定字符隔开的字符串*/
 #define AM_TOKEN_PARSE_BEGIN(_str, _delim, _token) \
-	{\
-	char *_strb =  strdup(_str);\
-	if (_strb) {\
-		_token = strtok(_strb, _delim);\
-		while (_token != NULL) {
+    {\
+    char *_strb =  strdup(_str);\
+    if (_strb) {\
+        _token = strtok(_strb, _delim);\
+        while (_token != NULL) {
 
 #define AM_TOKEN_PARSE_END(_str, _delim, _token) \
-		_token = strtok(NULL, _delim);\
-		}\
-		free(_strb);\
-	}\
-	}
+        _token = strtok(NULL, _delim);\
+        }\
+        free(_strb);\
+    }\
+    }
 
 
 /**\brief 从一个被指定字符隔开的字符串中取指定位置的值,int类型,如未找到指定位置,则使用默认值_default代替*/
 #define AM_TOKEN_VALUE_INT(_str, _delim, _index, _default) \
-	({\
-		char *token;\
-		char *_strbak = strdup(_str);\
-		int counter = 0;\
-		int val = _default;\
-		if (_strbak != NULL) {\
-			AM_TOKEN_PARSE_BEGIN(_strbak, _delim, token)\
-				if (counter == (_index)) {\
-					val = atoi(token);\
-					break;\
-				}\
-				counter++;\
-			AM_TOKEN_PARSE_END(_strbak, _delim, token)\
-			free(_strbak);\
-		}\
-		val;\
-	})
+    ({\
+        char *token;\
+        char *_strbak = strdup(_str);\
+        int counter = 0;\
+        int val = _default;\
+        if (_strbak != NULL) {\
+            AM_TOKEN_PARSE_BEGIN(_strbak, _delim, token)\
+                if (counter == (_index)) {\
+                    val = atoi(token);\
+                    break;\
+                }\
+                counter++;\
+            AM_TOKEN_PARSE_END(_strbak, _delim, token)\
+            free(_strbak);\
+        }\
+        val;\
+    })
 
 /****************************************************************************
  * Type definitions
diff --git a/test/am_ca_test/aml_key.h b/test/am_ca_test/aml_key.h
index 0be8210..6451739 100644
--- a/test/am_ca_test/aml_key.h
+++ b/test/am_ca_test/aml_key.h
@@ -19,46 +19,46 @@
 #define _AML_KEY_H_
 
 enum user_id {
-	DSC_LOC_DEC,
-	DSC_NETWORK,
-	DSC_LOC_ENC,
+    DSC_LOC_DEC,
+    DSC_NETWORK,
+    DSC_LOC_ENC,
 
-	CRYPTO_T0 = 0x100,
-	CRYPTO_T1 = 0x101,
-	CRYPTO_T2 = 0x102,
-	CRYPTO_T3 = 0x103,
-	CRYPTO_T4 = 0x104,
-	CRYPTO_T5 = 0x105,
+    CRYPTO_T0 = 0x100,
+    CRYPTO_T1 = 0x101,
+    CRYPTO_T2 = 0x102,
+    CRYPTO_T3 = 0x103,
+    CRYPTO_T4 = 0x104,
+    CRYPTO_T5 = 0x105,
 };
 
 enum key_algo {
-	KEY_ALGO_AES,
-	KEY_ALGO_TDES,
-	KEY_ALGO_DES,
-	KEY_ALGO_CSA2,
-	KEY_ALGO_CSA3,
-	KEY_ALGO_NDL,
-	KEY_ALGO_ND,
-	KEY_ALGO_S17
+    KEY_ALGO_AES,
+    KEY_ALGO_TDES,
+    KEY_ALGO_DES,
+    KEY_ALGO_CSA2,
+    KEY_ALGO_CSA3,
+    KEY_ALGO_NDL,
+    KEY_ALGO_ND,
+    KEY_ALGO_S17
 };
 
 struct key_descr {
-	unsigned int key_index;
-	unsigned int key_len;
-	unsigned char key[32];
+    unsigned int key_index;
+    unsigned int key_len;
+    unsigned char key[32];
 };
 
 struct key_config {
-	unsigned int key_index;
-	int key_userid;
-	int key_algo;
-	//cur just for s17 algo
-	unsigned int ext_value;
+    unsigned int key_index;
+    int key_userid;
+    int key_algo;
+    //cur just for s17 algo
+    unsigned int ext_value;
 };
 
 struct key_alloc {
-	int is_iv;
-	unsigned int key_index;
+    int is_iv;
+    unsigned int key_index;
 };
 
 #define KEY_ALLOC         _IOWR('o', 64, struct key_alloc)
diff --git a/test/am_ca_test/ca.h b/test/am_ca_test/ca.h
index 44dd659..d90f8ea 100644
--- a/test/am_ca_test/ca.h
+++ b/test/am_ca_test/ca.h
@@ -29,36 +29,36 @@
 /**
  * struct ca_slot_info - CA slot interface types and info.
  *
- * @num:	slot number.
- * @type:	slot type.
- * @flags:	flags applicable to the slot.
+ * @num:    slot number.
+ * @type:    slot type.
+ * @flags:    flags applicable to the slot.
  *
  * This struct stores the CA slot information.
  *
  * @type can be:
  *
- *	- %CA_CI - CI high level interface;
- *	- %CA_CI_LINK - CI link layer level interface;
- *	- %CA_CI_PHYS - CI physical layer level interface;
- *	- %CA_DESCR - built-in descrambler;
- *	- %CA_SC -simple smart card interface.
+ *    - %CA_CI - CI high level interface;
+ *    - %CA_CI_LINK - CI link layer level interface;
+ *    - %CA_CI_PHYS - CI physical layer level interface;
+ *    - %CA_DESCR - built-in descrambler;
+ *    - %CA_SC -simple smart card interface.
  *
  * @flags can be:
  *
- *	- %CA_CI_MODULE_PRESENT - module (or card) inserted;
- *	- %CA_CI_MODULE_READY - module is ready for usage.
+ *    - %CA_CI_MODULE_PRESENT - module (or card) inserted;
+ *    - %CA_CI_MODULE_READY - module is ready for usage.
  */
 
 struct ca_slot_info {
-	int num;
-	int type;
+    int num;
+    int type;
 #define CA_CI            1
 #define CA_CI_LINK       2
 #define CA_CI_PHYS       4
 #define CA_DESCR         8
 #define CA_SC          128
 
-	unsigned int flags;
+    unsigned int flags;
 #define CA_CI_MODULE_PRESENT 1
 #define CA_CI_MODULE_READY   2
 };
@@ -67,20 +67,20 @@
 /**
  * struct ca_descr_info - descrambler types and info.
  *
- * @num:	number of available descramblers (keys).
- * @type:	type of supported scrambling system.
+ * @num:    number of available descramblers (keys).
+ * @type:    type of supported scrambling system.
  *
  * Identifies the number of descramblers and their type.
  *
  * @type can be:
  *
- *	- %CA_ECD - European Common Descrambler (ECD) hardware;
- *	- %CA_NDS - Videoguard (NDS) hardware;
- *	- %CA_DSS - Distributed Sample Scrambling (DSS) hardware.
+ *    - %CA_ECD - European Common Descrambler (ECD) hardware;
+ *    - %CA_NDS - Videoguard (NDS) hardware;
+ *    - %CA_DSS - Distributed Sample Scrambling (DSS) hardware.
  */
 struct ca_descr_info {
-	unsigned int num;
-	unsigned int type;
+    unsigned int num;
+    unsigned int type;
 #define CA_ECD           1
 #define CA_NDS           2
 #define CA_DSS           4
@@ -89,35 +89,35 @@
 /**
  * struct ca_caps - CA slot interface capabilities.
  *
- * @slot_num:	total number of CA card and module slots.
- * @slot_type:	bitmap with all supported types as defined at
- *		&struct ca_slot_info (e. g. %CA_CI, %CA_CI_LINK, etc).
- * @descr_num:	total number of descrambler slots (keys)
- * @descr_type:	bitmap with all supported types as defined at
- *		&struct ca_descr_info (e. g. %CA_ECD, %CA_NDS, etc).
+ * @slot_num:    total number of CA card and module slots.
+ * @slot_type:    bitmap with all supported types as defined at
+ *        &struct ca_slot_info (e. g. %CA_CI, %CA_CI_LINK, etc).
+ * @descr_num:    total number of descrambler slots (keys)
+ * @descr_type:    bitmap with all supported types as defined at
+ *        &struct ca_descr_info (e. g. %CA_ECD, %CA_NDS, etc).
  */
 struct ca_caps {
-	unsigned int slot_num;
-	unsigned int slot_type;
-	unsigned int descr_num;
-	unsigned int descr_type;
+    unsigned int slot_num;
+    unsigned int slot_type;
+    unsigned int descr_num;
+    unsigned int descr_type;
 };
 
 /**
  * struct ca_msg - a message to/from a CI-CAM
  *
- * @index:	unused
- * @type:	unused
- * @length:	length of the message
- * @msg:	message
+ * @index:    unused
+ * @type:    unused
+ * @length:    length of the message
+ * @msg:    message
  *
  * This struct carries a message to be send/received from a CI CA module.
  */
 struct ca_msg {
-	unsigned int index;
-	unsigned int type;
-	unsigned int length;
-	unsigned char msg[256];
+    unsigned int index;
+    unsigned int type;
+    unsigned int length;
+    unsigned char msg[256];
 };
 
 /**
@@ -128,170 +128,170 @@
  * @cw: CA Descrambler control words
  */
 struct ca_descr {
-	unsigned int index;
-	unsigned int parity;
-	unsigned char cw[8];
+    unsigned int index;
+    unsigned int parity;
+    unsigned char cw[8];
 };
 
 #ifdef CONFIG_AMLOGIC_DVB_COMPAT
 /* CW type. */
 enum ca_cw_type {
-	CA_CW_DVB_CSA_EVEN,
-	CA_CW_DVB_CSA_ODD,
-	CA_CW_AES_EVEN,
-	CA_CW_AES_ODD,
-	CA_CW_AES_EVEN_IV,
-	CA_CW_AES_ODD_IV,
-	CA_CW_DES_EVEN,
-	CA_CW_DES_ODD,
-	CA_CW_SM4_EVEN,
-	CA_CW_SM4_ODD,
-	CA_CW_SM4_EVEN_IV,
-	CA_CW_SM4_ODD_IV,
-	CA_CW_TYPE_MAX
+    CA_CW_DVB_CSA_EVEN,
+    CA_CW_DVB_CSA_ODD,
+    CA_CW_AES_EVEN,
+    CA_CW_AES_ODD,
+    CA_CW_AES_EVEN_IV,
+    CA_CW_AES_ODD_IV,
+    CA_CW_DES_EVEN,
+    CA_CW_DES_ODD,
+    CA_CW_SM4_EVEN,
+    CA_CW_SM4_ODD,
+    CA_CW_SM4_EVEN_IV,
+    CA_CW_SM4_ODD_IV,
+    CA_CW_TYPE_MAX
 };
 
 enum ca_dsc_mode {
-	CA_DSC_CBC = 1,
-	CA_DSC_ECB,
-	CA_DSC_IDSA
+    CA_DSC_CBC = 1,
+    CA_DSC_ECB,
+    CA_DSC_IDSA
 };
 
 struct ca_descr_ex {
-	unsigned int index;
-	enum ca_cw_type type;
-	enum ca_dsc_mode mode;
-	int          flags;
+    unsigned int index;
+    enum ca_cw_type type;
+    enum ca_dsc_mode mode;
+    int          flags;
 #define CA_CW_FROM_KL 1
-	unsigned char cw[16];
+    unsigned char cw[16];
 };
 
 /* add for support sc2 ca*/
 enum ca_sc2_cmd_type {
-	CA_ALLOC,
-	CA_FREE,
-	CA_KEY,
-	CA_GET_STATUS,
-	CA_SET_SCB,
-	CA_SET_ALGO
+    CA_ALLOC,
+    CA_FREE,
+    CA_KEY,
+    CA_GET_STATUS,
+    CA_SET_SCB,
+    CA_SET_ALGO
 };
 
 enum ca_sc2_algo_type {
-	CA_ALGO_AES_ECB_CLR_END,
-	CA_ALGO_AES_ECB_CLR_FRONT,
-	CA_ALGO_AES_CBC_CLR_END,
-	CA_ALGO_AES_CBC_IDSA,
-	CA_ALGO_CSA2,
-	CA_ALGO_DES_SCTE41,
-	CA_ALGO_DES_SCTE52,
-	CA_ALGO_TDES_ECB_CLR_END,
-	CA_ALGO_CPCM_LSA_MDI_CBC,
-	CA_ALGO_CPCM_LSA_MDD_CBC,
-	CA_ALGO_CSA3,
-	CA_ALGO_ASA,
-	CA_ALGO_ASA_LIGHT,
-	CA_ALGO_S17_ECB_CLR_END,
-	CA_ALGO_S17_ECB_CTS,
-	CA_ALGO_UNKNOWN
+    CA_ALGO_AES_ECB_CLR_END,
+    CA_ALGO_AES_ECB_CLR_FRONT,
+    CA_ALGO_AES_CBC_CLR_END,
+    CA_ALGO_AES_CBC_IDSA,
+    CA_ALGO_CSA2,
+    CA_ALGO_DES_SCTE41,
+    CA_ALGO_DES_SCTE52,
+    CA_ALGO_TDES_ECB_CLR_END,
+    CA_ALGO_CPCM_LSA_MDI_CBC,
+    CA_ALGO_CPCM_LSA_MDD_CBC,
+    CA_ALGO_CSA3,
+    CA_ALGO_ASA,
+    CA_ALGO_ASA_LIGHT,
+    CA_ALGO_S17_ECB_CLR_END,
+    CA_ALGO_S17_ECB_CTS,
+    CA_ALGO_UNKNOWN
 };
 
 enum ca_sc2_dsc_type {
-	CA_DSC_COMMON_TYPE,
-	CA_DSC_TSD_TYPE,	/*just support AES descramble.*/
-	CA_DSC_TSE_TYPE		/*just support AES enscramble.*/
+    CA_DSC_COMMON_TYPE,
+    CA_DSC_TSD_TYPE,    /*just support AES descramble.*/
+    CA_DSC_TSE_TYPE        /*just support AES enscramble.*/
 };
 
 /**
  * struct ca_alloc - malloc ca slot index by params
  *
- * @pid:	slot use pid.
- * @algo:	use the algorithm
- * @dsc_type:	CA_DSC_COMMON_TYPE:support all ca_algo_type
- *		CA_DSC_TSD_TYPE & CA_DSC_TSE_TYPE just support AES
- * @ca_index:	return slot index.
+ * @pid:    slot use pid.
+ * @algo:    use the algorithm
+ * @dsc_type:    CA_DSC_COMMON_TYPE:support all ca_algo_type
+ *        CA_DSC_TSD_TYPE & CA_DSC_TSE_TYPE just support AES
+ * @ca_index:    return slot index.
  */
 struct ca_sc2_alloc {
-	unsigned int pid;
-	enum ca_sc2_algo_type algo;
-	enum ca_sc2_dsc_type dsc_type;
-	unsigned int ca_index;
+    unsigned int pid;
+    enum ca_sc2_algo_type algo;
+    enum ca_sc2_dsc_type dsc_type;
+    unsigned int ca_index;
 };
 
 /**
  * struct ca_sc2_free - free slot index
  *
- * @ca_index:	need free slot index.
+ * @ca_index:    need free slot index.
  */
 struct ca_sc2_free {
-	unsigned int ca_index;
+    unsigned int ca_index;
 };
 
 enum ca_sc2_key_type {
-	CA_KEY_EVEN_TYPE,
-	CA_KEY_EVEN_IV_TYPE,
-	CA_KEY_ODD_TYPE,
-	CA_KEY_ODD_IV_TYPE,
-	CA_KEY_00_TYPE,
-	CA_KEY_00_IV_TYPE
+    CA_KEY_EVEN_TYPE,
+    CA_KEY_EVEN_IV_TYPE,
+    CA_KEY_ODD_TYPE,
+    CA_KEY_ODD_IV_TYPE,
+    CA_KEY_00_TYPE,
+    CA_KEY_00_IV_TYPE
 };
 
 /**
  * struct ca_sc2_key - set key slot index
  *
- * @ca_index:	use slot index.
- * @parity:	key type (odd/even/key00)
+ * @ca_index:    use slot index.
+ * @parity:    key type (odd/even/key00)
  * @key_index: key store index.
  */
 struct ca_sc2_key {
-	unsigned int ca_index;
-	enum ca_sc2_key_type parity;
-	unsigned int key_index;
+    unsigned int ca_index;
+    enum ca_sc2_key_type parity;
+    unsigned int key_index;
 };
 
 /**
  * struct ca_sc2_scb - set scb
  *
- * @ca_index:	use slot index.
- * @ca_scb:	ca_scb (2bit)
+ * @ca_index:    use slot index.
+ * @ca_scb:    ca_scb (2bit)
  * @ca_scb_as_is:if 1, scb use original
- *				 if 0, use ca_scb
+ *                 if 0, use ca_scb
  */
 struct ca_sc2_scb {
-	unsigned int ca_index;
-	unsigned char ca_scb;
-	unsigned char ca_scb_as_is;
+    unsigned int ca_index;
+    unsigned char ca_scb;
+    unsigned char ca_scb_as_is;
 };
 
 /**
  * struct ca_sc2_algo - set algo
  *
- * @ca_index:	use slot index.
- * @algo:	algo
+ * @ca_index:    use slot index.
+ * @algo:    algo
  */
 struct ca_sc2_algo {
-	unsigned int ca_index;
-	enum ca_sc2_algo_type algo;
+    unsigned int ca_index;
+    enum ca_sc2_algo_type algo;
 };
 
 /**
- * struct ca_sc2_descr_ex - ca externd descriptor
+ * struct ca_sc2_descr_ex - ca extend descriptor
  *
- * @params:	command resource params
+ * @params:    command resource params
  */
 struct ca_sc2_descr_ex {
-	enum ca_sc2_cmd_type cmd;
-	union {
-		struct ca_sc2_alloc alloc_params;
-		struct ca_sc2_free free_params;
-		struct ca_sc2_key key_params;
-		struct ca_sc2_scb scb_params;
-		struct ca_sc2_algo algo_params;
-	} params;
+    enum ca_sc2_cmd_type cmd;
+    union {
+        struct ca_sc2_alloc alloc_params;
+        struct ca_sc2_free free_params;
+        struct ca_sc2_key key_params;
+        struct ca_sc2_scb scb_params;
+        struct ca_sc2_algo algo_params;
+    } params;
 };
 
 struct ca_pid {
-	unsigned int pid;
-	int index;   /* -1 == disable*/
+    unsigned int pid;
+    int index;   /* -1 == disable*/
 };
 
 #endif /*CONFIG_AMLOGIC_DVB_COMPAT*/
diff --git a/test/am_ca_test/dmx.h b/test/am_ca_test/dmx.h
index 874b524..ef97a48 100644
--- a/test/am_ca_test/dmx.h
+++ b/test/am_ca_test/dmx.h
@@ -35,51 +35,51 @@
 
 enum dmx_output
 {
-	DMX_OUT_DECODER, /* Streaming directly to decoder. */
-	DMX_OUT_TAP,     /* Output going to a memory buffer */
-			 /* (to be retrieved via the read command).*/
-	DMX_OUT_TS_TAP,  /* Output multiplexed into a new TS  */
-			 /* (to be retrieved by reading from the */
-			 /* logical DVR device).                 */
-	DMX_OUT_TSDEMUX_TAP /* Like TS_TAP but retrieved from the DMX device */
+    DMX_OUT_DECODER, /* Streaming directly to decoder. */
+    DMX_OUT_TAP,     /* Output going to a memory buffer */
+             /* (to be retrieved via the read command).*/
+    DMX_OUT_TS_TAP,  /* Output multiplexed into a new TS  */
+             /* (to be retrieved by reading from the */
+             /* logical DVR device).                 */
+    DMX_OUT_TSDEMUX_TAP /* Like TS_TAP but retrieved from the DMX device */
 };
 
 typedef enum dmx_output dmx_output_t;
 
 typedef enum dmx_input
 {
-	DMX_IN_FRONTEND, /* Input from a front-end device.  */
-	DMX_IN_DVR       /* Input from the logical DVR device.  */
+    DMX_IN_FRONTEND, /* Input from a front-end device.  */
+    DMX_IN_DVR       /* Input from the logical DVR device.  */
 } dmx_input_t;
 
 
 typedef enum dmx_ts_pes
 {
-	DMX_PES_AUDIO0,
-	DMX_PES_VIDEO0,
-	DMX_PES_TELETEXT0,
-	DMX_PES_SUBTITLE0,
-	DMX_PES_PCR0,
+    DMX_PES_AUDIO0,
+    DMX_PES_VIDEO0,
+    DMX_PES_TELETEXT0,
+    DMX_PES_SUBTITLE0,
+    DMX_PES_PCR0,
 
-	DMX_PES_AUDIO1,
-	DMX_PES_VIDEO1,
-	DMX_PES_TELETEXT1,
-	DMX_PES_SUBTITLE1,
-	DMX_PES_PCR1,
+    DMX_PES_AUDIO1,
+    DMX_PES_VIDEO1,
+    DMX_PES_TELETEXT1,
+    DMX_PES_SUBTITLE1,
+    DMX_PES_PCR1,
 
-	DMX_PES_AUDIO2,
-	DMX_PES_VIDEO2,
-	DMX_PES_TELETEXT2,
-	DMX_PES_SUBTITLE2,
-	DMX_PES_PCR2,
+    DMX_PES_AUDIO2,
+    DMX_PES_VIDEO2,
+    DMX_PES_TELETEXT2,
+    DMX_PES_SUBTITLE2,
+    DMX_PES_PCR2,
 
-	DMX_PES_AUDIO3,
-	DMX_PES_VIDEO3,
-	DMX_PES_TELETEXT3,
-	DMX_PES_SUBTITLE3,
-	DMX_PES_PCR3,
+    DMX_PES_AUDIO3,
+    DMX_PES_VIDEO3,
+    DMX_PES_TELETEXT3,
+    DMX_PES_SUBTITLE3,
+    DMX_PES_PCR3,
 
-	DMX_PES_OTHER
+    DMX_PES_OTHER
 } dmx_pes_type_t;
 
 #define DMX_PES_AUDIO    DMX_PES_AUDIO0
@@ -91,18 +91,18 @@
 
 typedef struct dmx_filter
 {
-	__u8  filter[DMX_FILTER_SIZE];
-	__u8  mask[DMX_FILTER_SIZE];
-	__u8  mode[DMX_FILTER_SIZE];
+    __u8  filter[DMX_FILTER_SIZE];
+    __u8  mask[DMX_FILTER_SIZE];
+    __u8  mode[DMX_FILTER_SIZE];
 } dmx_filter_t;
 
 
 struct dmx_sct_filter_params
 {
-	__u16          pid;
-	dmx_filter_t   filter;
-	__u32          timeout;
-	__u32          flags;
+    __u16          pid;
+    dmx_filter_t   filter;
+    __u32          timeout;
+    __u32          flags;
 #define DMX_CHECK_CRC       1
 #define DMX_ONESHOT         2
 #define DMX_IMMEDIATE_START 4
@@ -115,103 +115,103 @@
 #ifdef CONFIG_AMLOGIC_DVB_COMPAT
 
 enum dmx_input_source {
-	INPUT_DEMOD,
-	INPUT_LOCAL,
-	INPUT_LOCAL_SEC
+    INPUT_DEMOD,
+    INPUT_LOCAL,
+    INPUT_LOCAL_SEC
 };
 
 enum dmx_hw_source {
-	HW_TS0,
-	HW_TS1,
-	HW_TS2,
-	HW_TS3,
-	HW_TS4,
-	HW_TS5,
-	HW_TS6,
-	HW_TS7,
-	HW_DMA0 = 16,
-	HW_DMA1,
-	HW_DMA2,
-	HW_DMA3,
-	HW_DMA4,
-	HW_DMA5,
-	HW_DMA6,
-	HW_DMA7
+    HW_TS0,
+    HW_TS1,
+    HW_TS2,
+    HW_TS3,
+    HW_TS4,
+    HW_TS5,
+    HW_TS6,
+    HW_TS7,
+    HW_DMA0 = 16,
+    HW_DMA1,
+    HW_DMA2,
+    HW_DMA3,
+    HW_DMA4,
+    HW_DMA5,
+    HW_DMA6,
+    HW_DMA7
 };
 
 /**
  * struct dmx_non_sec_es_header - non-sec Elementary Stream (ES) Header
  *
  * @pts_dts_flag:[1:0], 01:pts valid, 10:dts valid
- * @pts:	pts value
- * @dts:	dts value
- * @len:	data len
+ * @pts:    pts value
+ * @dts:    dts value
+ * @len:    data len
  */
 struct dmx_non_sec_es_header {
-	__u8 pts_dts_flag;
-	__u64 pts;
-	__u64 dts;
-	__u32 len;
+    __u8 pts_dts_flag;
+    __u64 pts;
+    __u64 dts;
+    __u32 len;
 };
 
 /**
  * struct dmx_sec_es_data - sec Elementary Stream (ES)
  *
  * @pts_dts_flag:[1:0], 01:pts valid, 10:dts valid
- * @pts:	pts value
- * @dts:	dts value
- * @buf_start:	buf start addr
- * @buf_end:	buf end addr
+ * @pts:    pts value
+ * @dts:    dts value
+ * @buf_start:    buf start addr
+ * @buf_end:    buf end addr
  * @data_start: data start addr
  * @data_end: data end addr
  */
 struct dmx_sec_es_data {
-	__u8 pts_dts_flag;
-	__u64 pts;
-	__u64 dts;
-	__u32 buf_start;
-	__u32 buf_end;
-	__u32 data_start;
-	__u32 data_end;
+    __u8 pts_dts_flag;
+    __u64 pts;
+    __u64 dts;
+    __u32 buf_start;
+    __u32 buf_end;
+    __u32 data_start;
+    __u32 data_end;
 };
 
 enum dmx_audio_format {
-	AUDIO_UNKNOWN = 0,	/* unknown media */
-	AUDIO_MPX = 1,		/* mpeg audio MP2/MP3 */
-	AUDIO_AC3 = 2,		/* Dolby AC3/EAC3 */
-	AUDIO_AAC_ADTS = 3,	/* AAC-ADTS */
-	AUDIO_AAC_LOAS = 4,	/* AAC-LOAS */
-	AUDIO_DTS = 5,		/* DTS */
-	AUDIO_MAX
+    AUDIO_UNKNOWN = 0,    /* unknown media */
+    AUDIO_MPX = 1,        /* mpeg audio MP2/MP3 */
+    AUDIO_AC3 = 2,        /* Dolby AC3/EAC3 */
+    AUDIO_AAC_ADTS = 3,    /* AAC-ADTS */
+    AUDIO_AAC_LOAS = 4,    /* AAC-LOAS */
+    AUDIO_DTS = 5,        /* DTS */
+    AUDIO_MAX
 };
 
 struct dmx_mem_info {
-	__u32 dmx_total_size;
-	__u32 dmx_buf_phy_start;
-	__u32 dmx_free_size;
-	__u32 dvb_core_total_size;
-	__u32 dvb_core_free_size;
-	__u32 wp_offset;
+    __u32 dmx_total_size;
+    __u32 dmx_buf_phy_start;
+    __u32 dmx_free_size;
+    __u32 dvb_core_total_size;
+    __u32 dvb_core_free_size;
+    __u32 wp_offset;
 };
 
 #endif
 
 /**
  * struct dmx_pes_filter_params - Specifies Packetized Elementary Stream (PES)
- *	filter parameters.
+ *    filter parameters.
  *
- * @pid:	PID to be filtered.
- * @input:	Demux input, as specified by &enum dmx_input.
- * @output:	Demux output, as specified by &enum dmx_output.
- * @pes_type:	Type of the pes filter, as specified by &enum dmx_pes_type.
- * @flags:	Demux PES flags.
+ * @pid:    PID to be filtered.
+ * @input:    Demux input, as specified by &enum dmx_input.
+ * @output:    Demux output, as specified by &enum dmx_output.
+ * @pes_type:    Type of the pes filter, as specified by &enum dmx_pes_type.
+ * @flags:    Demux PES flags.
  */
 struct dmx_pes_filter_params {
-	__u16           pid;
-	dmx_input_t  input;
-	dmx_output_t output;
-	dmx_pes_type_t pes_type;
-	__u32           flags;
+    __u16           pid;
+    dmx_input_t  input;
+    dmx_output_t output;
+    dmx_pes_type_t pes_type;
+    __u32           flags;
 #ifdef CONFIG_AMLOGIC_DVB_COMPAT
 /*bit 8~15 for mem sec_level*/
 #define DMX_MEM_SEC_LEVEL1   (1 << 10)
@@ -221,7 +221,7 @@
 /*bit 16~23 for output */
 #define DMX_ES_OUTPUT        (1 << 16)
 /*set raw mode, it will send the struct dmx_sec_es_data, not es data*/
-#define DMX_OUTPUT_RAW_MODE	 (1 << 17)
+#define DMX_OUTPUT_RAW_MODE     (1 << 17)
 
 /*24~31 one byte for audio type, dmx_audio_format_t*/
 #define DMX_AUDIO_FORMAT_BIT 24
@@ -230,31 +230,31 @@
 };
 
 typedef struct dmx_caps {
-	__u32 caps;
-	int num_decoders;
+    __u32 caps;
+    int num_decoders;
 } dmx_caps_t;
 
 typedef enum dmx_source {
-	DMX_SOURCE_FRONT0 = 0,
-	DMX_SOURCE_FRONT1,
-	DMX_SOURCE_FRONT2,
-	DMX_SOURCE_FRONT3,
-	DMX_SOURCE_DVR0   = 16,
-	DMX_SOURCE_DVR1,
-	DMX_SOURCE_DVR2,
-	DMX_SOURCE_DVR3,
+    DMX_SOURCE_FRONT0 = 0,
+    DMX_SOURCE_FRONT1,
+    DMX_SOURCE_FRONT2,
+    DMX_SOURCE_FRONT3,
+    DMX_SOURCE_DVR0   = 16,
+    DMX_SOURCE_DVR1,
+    DMX_SOURCE_DVR2,
+    DMX_SOURCE_DVR3,
 
 #ifdef CONFIG_AMLOGIC_DVB_COMPAT
-	DMX_SOURCE_FRONT0_OFFSET = 100,
-	DMX_SOURCE_FRONT1_OFFSET,
-	DMX_SOURCE_FRONT2_OFFSET
+    DMX_SOURCE_FRONT0_OFFSET = 100,
+    DMX_SOURCE_FRONT1_OFFSET,
+    DMX_SOURCE_FRONT2_OFFSET
 #endif
 } dmx_source_t;
 
 struct dmx_stc {
-	unsigned int num;	/* input : which STC? 0..N */
-	unsigned int base;	/* output: divisor for stc to get 90 kHz clock */
-	__u64 stc;		/* output: stc in 'base'*90 kHz units */
+    unsigned int num;    /* input : which STC? 0..N */
+    unsigned int base;    /* output: divisor for stc to get 90 kHz clock */
+    __u64 stc;        /* output: stc in 'base'*90 kHz units */
 };
 
 #define DMX_START                _IO('o', 41)
diff --git a/test/am_ca_test/keytable_api.h b/test/am_ca_test/keytable_api.h
index b011ce9..b701aca 100644
--- a/test/am_ca_test/keytable_api.h
+++ b/test/am_ca_test/keytable_api.h
@@ -86,13 +86,13 @@
 #define KEY_FROM_REE_HOST    (0)
 
 typedef struct key_info_s {
-	int key_userid;
-	int key_algo;
-	int key_flag;
-	int key_level;
-	int tee_priv;
-	int key_source;
-	uint8_t key_data[16];
+    int key_userid;
+    int key_algo;
+    int key_flag;
+    int key_level;
+    int tee_priv;
+    int key_source;
+    uint8_t key_data[16];
 }key_info_t;
 
 int keytable_alloc(int key_source, int *kte);
diff --git a/test/am_ca_test/linux_dvb.c b/test/am_ca_test/linux_dvb.c
index dd500e9..d97b3be 100644
--- a/test/am_ca_test/linux_dvb.c
+++ b/test/am_ca_test/linux_dvb.c
@@ -36,17 +36,17 @@
 #include "dmx.h"
 
 #define open(a...)\
-	({\
-	 int ret, times=3;\
-	 do {\
+    ({\
+     int ret, times = 3;\
+     do {\
         ret = open(a);\
         if (ret == -1)\
         {\
            usleep(100*1000);\
         }\
-	 }while(ret==-1 && times--);\
-	 ret;\
-	 })
+     } while (ret == -1 && times--);\
+     ret;\
+     })
 
 /****************************************************************************
  * Type definitions
@@ -54,8 +54,8 @@
 
 typedef struct
 {
-	char   dev_name[32];
-	int    fd[DMX_FILTER_COUNT];
+    char   dev_name[32];
+    int    fd[DMX_FILTER_COUNT];
 } DVBDmx_t;
 
 /****************************************************************************
@@ -87,7 +87,7 @@
 .poll           = dvb_poll,
 .read           = dvb_read,
 .set_input     = dvb_set_input,
-.get_stc		= dvb_get_stc
+.get_stc        = dvb_get_stc
 };
 
 /****************************************************************************
@@ -96,257 +96,257 @@
 
 static AM_ErrorCode_t dvb_open(AM_DMX_Device_t *dev, const AM_DMX_OpenPara_t *para)
 {
-	DVBDmx_t *dmx;
-	int i;
+    DVBDmx_t *dmx;
+    int i;
 
-	UNUSED(para);
+    UNUSED(para);
 
-	dmx = (DVBDmx_t*)malloc(sizeof(DVBDmx_t));
-	if(!dmx)
-	{
-		printf("not enough memory");
-		return AM_DMX_ERR_NO_MEM;
-	}
-	
-	snprintf(dmx->dev_name, sizeof(dmx->dev_name), "/dev/dvb0.demux%d", dev->dev_no);
-	
-	for(i=0; i<DMX_FILTER_COUNT; i++)
-		dmx->fd[i] = -1;
-	
-	dev->drv_data = dmx;
-	return AM_SUCCESS;
+    dmx = (DVBDmx_t*)malloc(sizeof(DVBDmx_t));
+    if (!dmx)
+    {
+        printf("not enough memory");
+        return AM_DMX_ERR_NO_MEM;
+    }
+
+    snprintf(dmx->dev_name, sizeof(dmx->dev_name), "/dev/dvb0.demux%d", dev->dev_no);
+
+    for (i = 0; i < DMX_FILTER_COUNT; i++)
+        dmx->fd[i] = -1;
+
+    dev->drv_data = dmx;
+    return AM_SUCCESS;
 }
 
 static AM_ErrorCode_t dvb_close(AM_DMX_Device_t *dev)
 {
-	DVBDmx_t *dmx = (DVBDmx_t*)dev->drv_data;
-	
-	free(dmx);
-	return AM_SUCCESS;
+    DVBDmx_t *dmx = (DVBDmx_t*)dev->drv_data;
+
+    free(dmx);
+    return AM_SUCCESS;
 }
 
 static AM_ErrorCode_t dvb_alloc_filter(AM_DMX_Device_t *dev, AM_DMX_Filter_t *filter)
 {
-	DVBDmx_t *dmx = (DVBDmx_t*)dev->drv_data;
-	int fd;
+    DVBDmx_t *dmx = (DVBDmx_t*)dev->drv_data;
+    int fd;
 
-	fd = open(dmx->dev_name, O_RDWR);
-	if(fd==-1)
-	{
-		printf("cannot open \"%s\" (%s)", dmx->dev_name, strerror(errno));
-		return AM_DMX_ERR_CANNOT_OPEN_DEV;
-	}
-	
-	dmx->fd[filter->id] = fd;
+    fd = open(dmx->dev_name, O_RDWR);
+    if (fd == -1)
+    {
+        printf("cannot open \"%s\" (%s)", dmx->dev_name, strerror(errno));
+        return AM_DMX_ERR_CANNOT_OPEN_DEV;
+    }
 
-	filter->drv_data = (void*)(long)fd;
-	
-	return AM_SUCCESS;
+    dmx->fd[filter->id] = fd;
+
+    filter->drv_data = (void*)(long)fd;
+
+    return AM_SUCCESS;
 }
 
 static AM_ErrorCode_t dvb_free_filter(AM_DMX_Device_t *dev, AM_DMX_Filter_t *filter)
 {
-	DVBDmx_t *dmx = (DVBDmx_t*)dev->drv_data;
-	int fd = (long)filter->drv_data;
+    DVBDmx_t *dmx = (DVBDmx_t*)dev->drv_data;
+    int fd = (long)filter->drv_data;
 
-	close(fd);
-	dmx->fd[filter->id] = -1;
-	
-	return AM_SUCCESS;
+    close(fd);
+    dmx->fd[filter->id] = -1;
+
+    return AM_SUCCESS;
 }
 AM_ErrorCode_t dvb_get_stc(AM_DMX_Device_t *dev, AM_DMX_Filter_t *filter)
 {
-	int fd = (long)filter->drv_data;
-	int ret;
-	struct dmx_stc stc;
-	int i = 0;
+    int fd = (long)filter->drv_data;
+    int ret;
+    struct dmx_stc stc;
+    int i = 0;
 
-	UNUSED(dev);
+    UNUSED(dev);
 
-	for (i = 0; i < 3; i++)
-	{
-		memset(&stc, 0, sizeof(struct dmx_stc));
-		stc.num = i;		
-		ret = ioctl(fd, DMX_GET_STC, &stc);
-		if (ret == 0) {
-			printf("get stc num %d: base:0x%0x, stc:0x%lx\n", stc.num, stc.base, stc.stc);
-		} else {
-			printf("get stc %d, fail\n", i);
-		}
-	}
-	return 0;
+    for (i = 0; i < 3; i++)
+    {
+        memset(&stc, 0, sizeof(struct dmx_stc));
+        stc.num = i;
+        ret = ioctl(fd, DMX_GET_STC, &stc);
+        if (ret == 0) {
+            printf("get stc num %d: base:0x%0x, stc:0x%lx\n", stc.num, stc.base, stc.stc);
+        } else {
+            printf("get stc %d, fail\n", i);
+        }
+    }
+    return 0;
 }
 
 static AM_ErrorCode_t dvb_set_sec_filter(AM_DMX_Device_t *dev, AM_DMX_Filter_t *filter, const struct dmx_sct_filter_params *params)
 {
-	struct dmx_sct_filter_params p;
-	int fd = (long)filter->drv_data;
-	int ret;
+    struct dmx_sct_filter_params p;
+    int fd = (long)filter->drv_data;
+    int ret;
 
-	UNUSED(dev);
+    UNUSED(dev);
 
-	p = *params;
-	/*
-	if(p.filter.mask[0] == 0){
-		p.filter.filter[0] = 0x00;
-		p.filter.mask[0]   = 0x80;
-	}
-	*/
-	ret = ioctl(fd, DMX_SET_FILTER, &p);
-	if(ret==-1)
-	{
-		printf("set section filter failed (%s)", strerror(errno));
-		return AM_DMX_ERR_SYS;
-	}
-	
-	return AM_SUCCESS;
+    p = *params;
+    /*
+    if (p.filter.mask[0] == 0) {
+        p.filter.filter[0] = 0x00;
+        p.filter.mask[0]   = 0x80;
+    }
+    */
+    ret = ioctl(fd, DMX_SET_FILTER, &p);
+    if (ret == -1)
+    {
+        printf("set section filter failed (%s)", strerror(errno));
+        return AM_DMX_ERR_SYS;
+    }
+
+    return AM_SUCCESS;
 }
 
 static AM_ErrorCode_t dvb_set_pes_filter(AM_DMX_Device_t *dev, AM_DMX_Filter_t *filter, const struct dmx_pes_filter_params *params)
 {
-	int fd = (long)filter->drv_data;
-	int ret;
+    int fd = (long)filter->drv_data;
+    int ret;
 
-	UNUSED(dev);
+    UNUSED(dev);
 
-	fcntl(fd,F_SETFL,O_NONBLOCK);
+    fcntl(fd,F_SETFL,O_NONBLOCK);
 
-	ret = ioctl(fd, DMX_SET_PES_FILTER, params);
-	if(ret==-1)
-	{
-		printf("set section filter failed (%s)", strerror(errno));
-		return AM_DMX_ERR_SYS;
-	}
-	printf("%s success\n", __FUNCTION__);
-	return AM_SUCCESS;
+    ret = ioctl(fd, DMX_SET_PES_FILTER, params);
+    if (ret == -1)
+    {
+        printf("set section filter failed (%s)", strerror(errno));
+        return AM_DMX_ERR_SYS;
+    }
+    printf("%s success\n", __FUNCTION__);
+    return AM_SUCCESS;
 }
 
 static AM_ErrorCode_t dvb_enable_filter(AM_DMX_Device_t *dev, AM_DMX_Filter_t *filter, AM_Bool_t enable)
 {
-	int fd = (long)filter->drv_data;
-	int ret;
+    int fd = (long)filter->drv_data;
+    int ret;
 
-	UNUSED(dev);
+    UNUSED(dev);
 
-	if(enable)
-		ret = ioctl(fd, DMX_START, 0);
-	else
-		ret = ioctl(fd, DMX_STOP, 0);
-	
-	if(ret==-1)
-	{
-		printf("start filter failed (%s)", strerror(errno));
-		return AM_DMX_ERR_SYS;
-	}
-	
-	return AM_SUCCESS;
+    if (enable)
+        ret = ioctl(fd, DMX_START, 0);
+    else
+        ret = ioctl(fd, DMX_STOP, 0);
+
+    if (ret == -1)
+    {
+        printf("start filter failed (%s)", strerror(errno));
+        return AM_DMX_ERR_SYS;
+    }
+
+    return AM_SUCCESS;
 }
 
 static AM_ErrorCode_t dvb_set_buf_size(AM_DMX_Device_t *dev, AM_DMX_Filter_t *filter, int size)
 {
-	int fd = (long)filter->drv_data;
-	int ret;
+    int fd = (long)filter->drv_data;
+    int ret;
 
-	UNUSED(dev);
-	
-	ret = ioctl(fd, DMX_SET_BUFFER_SIZE, size);
-	if(ret==-1)
-	{
-		printf("set buffer size failed (%s)", strerror(errno));
-		return AM_DMX_ERR_SYS;
-	}
-	
-	return AM_SUCCESS;
+    UNUSED(dev);
+
+    ret = ioctl(fd, DMX_SET_BUFFER_SIZE, size);
+    if (ret == -1)
+    {
+        printf("set buffer size failed (%s)", strerror(errno));
+        return AM_DMX_ERR_SYS;
+    }
+
+    return AM_SUCCESS;
 }
 
 static AM_ErrorCode_t dvb_poll(AM_DMX_Device_t *dev, AM_DMX_FilterMask_t *mask, int timeout)
 {
-	DVBDmx_t *dmx = (DVBDmx_t*)dev->drv_data;
-	struct pollfd fds[DMX_FILTER_COUNT];
-	int fids[DMX_FILTER_COUNT];
-	int i, cnt = 0, ret;
-	
-	for(i=0; i<DMX_FILTER_COUNT; i++)
-	{
-		if(dmx->fd[i]!=-1)
-		{
-			fds[cnt].events = POLLIN|POLLERR;
-			fds[cnt].fd     = dmx->fd[i];
-			fids[cnt] = i;
-			cnt++;
-		}
-	}
-	
-	if(!cnt)
-		return AM_DMX_ERR_TIMEOUT;
-	
-	ret = poll(fds, cnt, timeout);
-	if(ret<=0)
-	{
-		return AM_DMX_ERR_TIMEOUT;
-	}
-	
-	for(i=0; i<cnt; i++)
-	{
-		if(fds[i].revents&(POLLIN|POLLERR))
-		{
-			AM_DMX_FILTER_MASK_SET(mask, fids[i]);
-		}
-	}
-	
-	return AM_SUCCESS;
+    DVBDmx_t *dmx = (DVBDmx_t*)dev->drv_data;
+    struct pollfd fds[DMX_FILTER_COUNT];
+    int fids[DMX_FILTER_COUNT];
+    int i, cnt = 0, ret;
+
+    for (i = 0; i < DMX_FILTER_COUNT; i++)
+    {
+        if (dmx->fd[i] != -1)
+        {
+            fds[cnt].events = POLLIN|POLLERR;
+            fds[cnt].fd     = dmx->fd[i];
+            fids[cnt] = i;
+            cnt++;
+        }
+    }
+
+    if (!cnt)
+        return AM_DMX_ERR_TIMEOUT;
+
+    ret = poll(fds, cnt, timeout);
+    if (ret <= 0)
+    {
+        return AM_DMX_ERR_TIMEOUT;
+    }
+
+    for (i = 0; i < cnt; i++)
+    {
+        if (fds[i].revents & (POLLIN | POLLERR))
+        {
+            AM_DMX_FILTER_MASK_SET(mask, fids[i]);
+        }
+    }
+
+    return AM_SUCCESS;
 }
 
 static AM_ErrorCode_t dvb_read(AM_DMX_Device_t *dev, AM_DMX_Filter_t *filter, uint8_t *buf, int *size)
 {
-	int fd = (long)filter->drv_data;
-	int len = *size;
-	int ret;
-	struct pollfd pfd;
+    int fd = (long)filter->drv_data;
+    int len = *size;
+    int ret;
+    struct pollfd pfd;
 
-	UNUSED(dev);
-	
-	if(fd==-1)
-		return AM_DMX_ERR_NOT_ALLOCATED;
-	
-	pfd.events = POLLIN|POLLERR;
-	pfd.fd     = fd;
-	
-	ret = poll(&pfd, 1, 0);
-	if(ret<=0)
-		return AM_DMX_ERR_NO_DATA;
-	
-	ret = read(fd, buf, len);
-	if(ret<=0)
-	{
-		if(errno==ETIMEDOUT)
-			return AM_DMX_ERR_TIMEOUT;
-		printf("read demux failed (%s) %d", strerror(errno), errno);
-		return AM_DMX_ERR_SYS;
-	}
-	
-	*size = ret;
-	return AM_SUCCESS;
+    UNUSED(dev);
+
+    if (fd == -1)
+        return AM_DMX_ERR_NOT_ALLOCATED;
+
+    pfd.events = POLLIN | POLLERR;
+    pfd.fd     = fd;
+
+    ret = poll(&pfd, 1, 0);
+    if (ret <= 0)
+        return AM_DMX_ERR_NO_DATA;
+
+    ret = read(fd, buf, len);
+    if (ret <= 0)
+    {
+        if (errno == ETIMEDOUT)
+            return AM_DMX_ERR_TIMEOUT;
+        printf("read demux failed (%s) %d", strerror(errno), errno);
+        return AM_DMX_ERR_SYS;
+    }
+
+    *size = ret;
+    return AM_SUCCESS;
 }
 
 static AM_ErrorCode_t dvb_set_input(AM_DMX_Device_t *dev, int input)
 {
-	int ret;
-	int fd = 0;
-	DVBDmx_t *dmx = (DVBDmx_t*)dev->drv_data;
+    int ret;
+    int fd = 0;
+    DVBDmx_t *dmx = (DVBDmx_t*)dev->drv_data;
 
-	fd = open(dmx->dev_name, O_RDWR);
-	if(fd == -1)
-	{
-		printf("cannot open for set input \"%s\" (%s)", dmx->dev_name, strerror(errno));
-		return AM_DMX_ERR_CANNOT_OPEN_DEV;
-	}
+    fd = open(dmx->dev_name, O_RDWR);
+    if (fd == -1)
+    {
+        printf("cannot open for set input \"%s\" (%s)", dmx->dev_name, strerror(errno));
+        return AM_DMX_ERR_CANNOT_OPEN_DEV;
+    }
 
-	ret = ioctl(fd, DMX_SET_INPUT, input);
-	
-	printf("dmx set_input ret:%d, input:%d\n", ret, input);
+    ret = ioctl(fd, DMX_SET_INPUT, input);
 
-	close(fd);
-	return 0;
+    printf("dmx set_input ret:%d, input:%d\n", ret, input);
+
+    close(fd);
+    return 0;
 }
 
diff --git a/test/am_dmx_test/am_dmx_test.c b/test/am_dmx_test/am_dmx_test.c
index 5e5d712..2cecd9b 100644
--- a/test/am_dmx_test/am_dmx_test.c
+++ b/test/am_dmx_test/am_dmx_test.c
@@ -8,7 +8,7 @@
  *
  * \section Usage
  *
- * \li src: demux source 
+ * \li src: demux source
  * \li dmx: demux device id
  * \li pat: 1     //filter for this table
  * \li eit: 1     //filter for this table
@@ -27,22 +27,22 @@
  *
  * demux section PSI/SI:
  * \code
- *	 am_dmx_test [src=] [dmx=] [pat=1] [timeout=]
+ *     am_dmx_test [src=] [dmx=] [pat=1] [timeout=]
  * \endcode
  * \code
- *	 am_dmx_test [src=] [dmx=] [eit=1] [timeout=]
+ *     am_dmx_test [src=] [dmx=] [eit=1] [timeout=]
  * \endcode
  * \code
- *	 am_dmx_test [src=] [dmx=] [nit=1] [timeout=]
+ *     am_dmx_test [src=] [dmx=] [nit=1] [timeout=]
  * \endcode
  * \code
- *	 am_dmx_test [src=] [dmx=] [bat=1] [timeout=]
+ *     am_dmx_test [src=] [dmx=] [bat=1] [timeout=]
  * \endcode
  *
  *
  * demux section PID:
  * \code
- *	 am_dmx_test [src=] [dmx=] [pidx=] [extx=] [bsx=] [timeout=]
+ *     am_dmx_test [src=] [dmx=] [pidx=] [extx=] [bsx=] [timeout=]
  * \endcode
  *
  * \endsection
@@ -81,25 +81,25 @@
 #define  BAT_TEST
 
 
-static int s_last_num =-1;
+static int s_last_num = -1;
 
 int layer = -1;
-int src=0;
-int dmx=0;
-int timeout = 60*3;
+int src = 0;
+int dmx = 0;
+int timeout = 60 * 3;
 
-static int bat=0;
-static int nit=0;
-static int user=0;
-static int pat=0;
-static int eit=0;
-static int pall=0;
+static int bat = 0;
+static int nit = 0;
+static int user = 0;
+static int pat = 0;
+static int eit = 0;
+static int pall = 0;
 
 #define USER_MAX 10
-static int u_pid[USER_MAX]={[0 ... USER_MAX-1] = -1};
-static int u_para[USER_MAX]={[0 ... USER_MAX-1] = 0};
-static char *u_ext[USER_MAX]={[0 ... USER_MAX-1] = NULL};
-static int u_bs[USER_MAX]={[0 ... USER_MAX-1] = 0};
+static int u_pid[USER_MAX] = {[0 ... USER_MAX-1] = -1};
+static int u_para[USER_MAX] = {[0 ... USER_MAX-1] = 0};
+static char *u_ext[USER_MAX] = {[0 ... USER_MAX-1] = NULL};
+static int u_bs[USER_MAX] = {[0 ... USER_MAX-1] = 0};
 static int u_para_g;
 static FILE *fp[USER_MAX];
 static FILE *fp_e[USER_MAX];
@@ -110,497 +110,495 @@
 static char u_path_g_b[256];
 /*
    u_para format:
-	d1 - 0:sec 1:pes
-	d2 - 1:crc : sec only
-	d3 - 1:print
-	d4 - 1:swfilter
-	d5 - 1:ts_tap :pes only
-	d6 - 1:w2file
+    d1 - 0:sec 1:pes
+    d2 - 1:crc : sec only
+    d3 - 1:print
+    d4 - 1:swfilter
+    d5 - 1:ts_tap :pes only
+    d6 - 1:w2file
 */
-#define UPARA_TYPE      0xf
-#define UPARA_CRC       0xf0
-#define UPARA_PR        0xf00
-#define UPARA_SF        0xf000
-#define UPARA_DMX_TAP   0xf0000
-#define UPARA_FILE      0xf00000
-#define UPARA_PES2ES    0xf000000
+#define PARA_TYPE      0xf
+#define PARA_CRC       0xf0
+#define PARA_PR        0xf00
+#define PARA_SF        0xf000
+#define PARA_DMX_TAP   0xf0000
+#define PARA_FILE      0xf00000
+#define PARA_PES2ES    0xf000000
 
-#define get_upara(_i) (u_para[(_i)]? u_para[(_i)] : u_para_g)
+#define get_u_para(_i) (u_para[(_i)] ? u_para[(_i)] : u_para_g)
 
 #define AML_MACRO_BEGIN   do {
-#define AML_MACRO_END     } while(0)
+#define AML_MACRO_END     } while (0)
 #define AM_TRY(_func) \
-	AML_MACRO_BEGIN\
-	DVB_RESULT _ret;\
-	if ((_ret=(_func))!=DVB_SUCCESS)\
-	{\
-	    printf("error line:%d ret:%d\n", __LINE__, _ret);\
-		return _ret;\
-	}\
-	AML_MACRO_END
+    AML_MACRO_BEGIN\
+    DVB_RESULT _ret;\
+    if ((_ret = (_func)) != DVB_SUCCESS)\
+    {\
+        printf("error line:%d ret:%d\n", __LINE__, _ret);\
+        return _ret;\
+    }\
+    AML_MACRO_END
 
 #if 0
 static void pes_cb(AM_PES_Handle_t handle, uint8_t *buf, int size) {
-	int u = (int)(long)AM_PES_GetUserData(handle);
-	printf("pes cb u=%d b=%p, s:%d\n", u, buf, size);
-	int ret = fwrite(buf, 1, size, fp_e[u-1]);
-	if (ret != size)
-		printf("data w lost\n");
+    int u = (int)(long)AM_PES_GetUserData(handle);
+    printf("pes cb u = %d b = %p, s:%d\n", u, buf, size);
+    int ret = fwrite(buf, 1, size, fp_e[u - 1]);
+    if (ret != size)
+        printf("data w lost\n");
 }
 #endif
 static void dump_bytes(int dev_no, int fid, const uint8_t *data, int len, void *user_data)
 {
-	int u = (int)(long)user_data;
+    int u = (int)(long)user_data;
 
-	if(pall) {
-		int i;
-		printf("data:\n");
-		for(i=0;i<len;i++)
-		{
-			printf("%02x ", data[i]);
-			if(((i+1)%16)==0) printf("\n");
-		}
-		if((i%16)!=0) printf("\n");
-	}
+    if (pall) {
+        int i;
+        printf("data:\n");
+        for (i = 0; i < len; i++)
+        {
+            printf("%02x ", data[i]);
+            if (((i + 1) % 16) == 0) printf("\n");
+        }
+        if ((i % 16) != 0) printf("\n");
+    }
 #if 1
-	if(bat&UPARA_PR) {
-		if(data[0]==0x4a) {
-			printf("sec:tabid:0x%02x,bunqid:0x%02x%02x,section num:%4d,lat_section_num:%4d\n",data[0],
-				data[3],data[4],data[6],data[7]);
-		}
+    if (bat & PARA_PR) {
+        if (data[0] == 0x4a) {
+            printf("sec:tabid:0x%02x,bouquet_id:0x%02x%02x,section num:%4d,lat_section_num:%4d\n", data[0],
+                data[3], data[4], data[6], data[7]);
+        }
 
-	}
-	else if(nit&UPARA_PR) {
+    }
+    else if (nit & PARA_PR) {
 
-		if(data[0]==0x40) {
-			printf("section:%8d,max:%8d\n",data[6],data[7]);
-			if((data[6] !=s_last_num+1)&&(s_last_num!=-1))//��һ�����߲�����
-			{
-				if(s_last_num ==data[7])//��һ����MAX
-				{
-					if(data[6] != 0)//��һ��MAX ������� 0
-					{
-						printf("##drop packet,tabid:0x%4x,cur:%8d,last:%8d,max:%8d\n",data[0],
-						data[6],s_last_num,data[7]);
-						//stop_section_flag =1;
-					}
-					else
-					{
-					}
-				}
-				else//��һ������
-				{
-					printf("##drop packet,tabid:%4x,cur:%8d,last:%8d,max:%8d\n",data[0],
-					data[6],s_last_num,data[7]);
-					//stop_section_flag =1;
-				}
-
-				
-			}
-			else
-			{
-				//printf("section:%8d,",sectiondata->m_pucData[6]);
-			}
-			s_last_num = data[6];
-		}
-	}
-	else if(pat&UPARA_PR) {
-		if(data[0]==0x0)
-			printf("%02x: %02x %02x %02x %02x %02x %02x %02x %02x\n", data[0], data[1], data[2], data[3], data[4],
-				data[5], data[6], data[7], data[8]);
-	}
-	else {
-		if(!user_data) {
-			printf("%02x %02x %02x %02x %02x %02x %02x %02x %02x\n", data[0], data[1], data[2], data[3], data[4],
-				data[5], data[6], data[7], data[8]);
-			return;
-		}
+        if (data[0] == 0x40) {
+            printf("section:%8d,max:%8d\n", data[6], data[7]);
+            if ((data[6] != s_last_num + 1) && (s_last_num != -1))//��һ�����߲�����
+            {
+                if (s_last_num == data[7])//��һ����MAX
+                {
+                    if (data[6] != 0)//��һ��MAX ������� 0
+                    {
+                        printf("##drop packet,tabid:0x%4x,cur:%8d,last:%8d,max:%8d\n", data[0],
+                        data[6], s_last_num, data[7]);
+                        //stop_section_flag = 1;
+                    }
+                    else
+                    {
+                    }
+                }
+                else//��һ������
+                {
+                    printf("##drop packet,tabid:%4x,cur:%8d,last:%8d,max:%8d\n", data[0],
+                    data[6], s_last_num, data[7]);
+                    //stop_section_flag = 1;
+                }
+            }
+            else
+            {
+                //printf("section:%8d,", sectiondata->m_pucData[6]);
+            }
+            s_last_num = data[6];
+        }
+    }
+    else if (pat & PARA_PR) {
+        if (data[0] == 0x0)
+            printf("%02x: %02x %02x %02x %02x %02x %02x %02x %02x\n", data[0], data[1], data[2], data[3], data[4],
+                data[5], data[6], data[7], data[8]);
+    }
+    else {
+        if (!user_data) {
+            printf("%02x %02x %02x %02x %02x %02x %02x %02x %02x\n", data[0], data[1], data[2], data[3], data[4],
+                data[5], data[6], data[7], data[8]);
+            return;
+        }
 #if 0
-		if(get_upara(u-1)&UPARA_PR)
-			printf("[%d:%d %d] %02x %02x %02x %02x %02x %02x %02x %02x %02x\n", u-1, u_pid[u-1], len,
-				data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8]);
-		if(get_upara(u-1)&UPARA_FILE){
-			{
-				int ret = fwrite(data, 1, len, fp[u-1]);
-				if (ret != len)
-					printf("data w lost\n");
-			}
-			if (get_upara(u-1)&UPARA_PES2ES) {
-				if (!h_pes[u-1]) {
-					AM_PES_Para_t para = {.packet = pes_cb, .user_data = (void*)(long)u, .payload_only = AM_TRUE,};
-					AM_PES_Create(&h_pes[u-1], &para);
-				}
-				AM_PES_Decode(h_pes[u-1], data, len);
-			}
-		}
+        if (get_u_para(u - 1) & PARA_PR)
+            printf("[%d:%d %d] %02x %02x %02x %02x %02x %02x %02x %02x %02x\n", u - 1, u_pid[u - 1], len,
+                data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8]);
+        if (get_u_para(u - 1) & PARA_FILE) {
+            {
+                int ret = fwrite(data, 1, len, fp[u - 1]);
+                if (ret != len)
+                    printf("data w lost\n");
+            }
+            if (get_u_para(u - 1) & PARA_PES2ES) {
+                if (!h_pes[u - 1]) {
+                    AM_PES_Para_t para = {.packet = pes_cb, .user_data = (void*)(long)u, .payload_only = AM_TRUE,};
+                    AM_PES_Create(&h_pes[u - 1], &para);
+                }
+                AM_PES_Decode(h_pes[u - 1], data, len);
+            }
+        }
 #endif
-	}
+    }
 #endif
 }
 
 static int get_section(int dmx, int timeout)
 {
 #ifdef PAT_TEST
-	int fid;
+    int fid;
 #endif
 
 #ifdef EIT_TEST
-	int fid_eit_pf, fid_eit_opf;
+    int fid_eit_pf, fid_eit_opf;
 #endif
 
 #ifdef NIT_TEST
-	int fid_nit;
+    int fid_nit;
 #endif
 #ifdef BAT_TEST
-	int fid_bat;
+    int fid_bat;
 #endif
 
-	int fid_user[USER_MAX];
-	int i;
+    int fid_user[USER_MAX] = {0};
+    int i;
 
-	struct dmx_sct_filter_params param;
-	struct dmx_pes_filter_params pparam;
+    struct dmx_sct_filter_params param;
+    struct dmx_pes_filter_params pparam;
 #ifdef PAT_TEST
-	if(pat&0xf) {
-	printf("start pat...\n");
-	AM_TRY(AML_DMX_AllocateFilter(dmx, &fid));
-	AM_TRY(AML_DMX_SetCallback(dmx, fid, dump_bytes, NULL));
-	}
+    if (pat & 0xf) {
+    printf("start pat...\n");
+    AM_TRY(AML_DMX_AllocateFilter(dmx, &fid));
+    AM_TRY(AML_DMX_SetCallback(dmx, fid, dump_bytes, NULL));
+    }
 #endif
 
 #ifdef EIT_TEST
-	if(eit&0xf) {
-	printf("start eit...\n");
-	AM_TRY(AML_DMX_AllocateFilter(dmx, &fid_eit_pf));
-	AM_TRY(AML_DMX_SetCallback(dmx, fid_eit_pf, dump_bytes, NULL));
-	AM_TRY(AML_DMX_AllocateFilter(dmx, &fid_eit_opf));
-	AM_TRY(AML_DMX_SetCallback(dmx, fid_eit_opf, dump_bytes, NULL));
-	}
+    if (eit & 0xf) {
+    printf("start eit...\n");
+    AM_TRY(AML_DMX_AllocateFilter(dmx, &fid_eit_pf));
+    AM_TRY(AML_DMX_SetCallback(dmx, fid_eit_pf, dump_bytes, NULL));
+    AM_TRY(AML_DMX_AllocateFilter(dmx, &fid_eit_opf));
+    AM_TRY(AML_DMX_SetCallback(dmx, fid_eit_opf, dump_bytes, NULL));
+    }
 #endif
 
 #ifdef NIT_TEST
-	if(nit&0xf) {
-	printf("start nit...\n");
-	AM_TRY(AML_DMX_AllocateFilter(dmx, &fid_nit));
-	AM_TRY(AML_DMX_SetCallback(dmx, fid_nit, dump_bytes, NULL));
-	}
+    if (nit & 0xf) {
+    printf("start nit...\n");
+    AM_TRY(AML_DMX_AllocateFilter(dmx, &fid_nit));
+    AM_TRY(AML_DMX_SetCallback(dmx, fid_nit, dump_bytes, NULL));
+    }
 #endif
 
 #ifdef BAT_TEST
-	if(bat&0xf) {
-	printf("start bat...\n");
-	AM_TRY(AML_DMX_AllocateFilter(dmx, &fid_bat));
-	AM_TRY(AML_DMX_SetCallback(dmx, fid_bat, dump_bytes, NULL));
-	}
-#endif
-
-	
-#ifdef PAT_TEST
-	if(pat&0xf) {
-	memset(&param, 0, sizeof(param));
-	param.pid = 0;
-	param.filter.filter[0] = 0;
-	param.filter.mask[0] = 0xff;
-	//param.filter.filter[2] = 0x08;
-	//param.filter.mask[2] = 0xff;
-
-	param.flags = DMX_CHECK_CRC;
-	if(pat&UPARA_SF)
-		param.flags |= 0x100;
-	AM_TRY(AML_DMX_SetSecFilter(dmx, fid, &param));
-	}
-#endif
-
-#ifdef EIT_TEST
-	if(eit&0xf) {
-	memset(&param, 0, sizeof(param));
-	param.pid = 0x12;
-	param.filter.filter[0] = 0x4E;
-	param.filter.mask[0] = 0xff;
-	param.flags = DMX_CHECK_CRC;	
-	if(eit&UPARA_SF)
-		param.flags |= 0x100;
-	AM_TRY(AML_DMX_SetSecFilter(dmx, fid_eit_pf, &param));
-	
-	memset(&param, 0, sizeof(param));
-	param.pid = 0x12;
-	param.filter.filter[0] = 0x4F;
-	param.filter.mask[0] = 0xff;
-	param.flags = DMX_CHECK_CRC;	
-	if(eit&UPARA_SF)
-		param.flags |= 0x100;
-	AM_TRY(AML_DMX_SetSecFilter(dmx, fid_eit_opf, &param));
-	}
-#endif
-
-#ifdef NIT_TEST
-	if(nit&0xF) {
-	memset(&param, 0, sizeof(param));
-	param.pid = 0x10;
-	param.filter.filter[0] = 0x40;
-	param.filter.mask[0] = 0xff;
-	if(nit&UPARA_CRC)
-		param.flags = DMX_CHECK_CRC;	
-	if(nit&UPARA_SF)
-		param.flags |= 0x100;
-	AM_TRY(AML_DMX_SetSecFilter(dmx, fid_nit, &param));
-	}
-#endif
-
-#ifdef BAT_TEST
-	if(bat&0xF) {
-	memset(&param, 0, sizeof(param));
-	param.pid = 0x11;
-	param.filter.filter[0] = 0x4a;
-	param.filter.mask[0] = 0xff;
-	if(bat&UPARA_CRC)
-		param.flags = DMX_CHECK_CRC;	
-	if(bat&UPARA_SF)
-		param.flags |= 0x100;
-	AM_TRY(AML_DMX_SetSecFilter(dmx, fid_bat, &param));
-	}
+    if (bat & 0xf) {
+    printf("start bat...\n");
+    AM_TRY(AML_DMX_AllocateFilter(dmx, &fid_bat));
+    AM_TRY(AML_DMX_SetCallback(dmx, fid_bat, dump_bytes, NULL));
+    }
 #endif
 
 
 #ifdef PAT_TEST
-	if(pat&0xF) {
-	AM_TRY(AML_DMX_SetBufferSize(dmx, fid, 32*1024));
-	AM_TRY(AML_DMX_StartFilter(dmx, fid));
-	}
+    if (pat & 0xf) {
+    memset(&param, 0, sizeof(param));
+    param.pid = 0;
+    param.filter.filter[0] = 0;
+    param.filter.mask[0] = 0xff;
+    //param.filter.filter[2] = 0x08;
+    //param.filter.mask[2] = 0xff;
+
+    param.flags = DMX_CHECK_CRC;
+    if (pat & PARA_SF)
+        param.flags |= 0x100;
+    AM_TRY(AML_DMX_SetSecFilter(dmx, fid, &param));
+    }
 #endif
+
 #ifdef EIT_TEST
-	if(eit&0xF) {
-	AM_TRY(AML_DMX_SetBufferSize(dmx, fid_eit_pf, 32*1024));
-	AM_TRY(AML_DMX_StartFilter(dmx, fid_eit_pf));
-	AM_TRY(AML_DMX_SetBufferSize(dmx, fid_eit_opf, 32*1024));
-	//AM_TRY(AML_DMX_StartFilter(dmx, fid_eit_opf));
-	}
+    if (eit & 0xf) {
+    memset(&param, 0, sizeof(param));
+    param.pid = 0x12;
+    param.filter.filter[0] = 0x4E;
+    param.filter.mask[0] = 0xff;
+    param.flags = DMX_CHECK_CRC;
+    if (eit & PARA_SF)
+        param.flags |= 0x100;
+    AM_TRY(AML_DMX_SetSecFilter(dmx, fid_eit_pf, &param));
+
+    memset(&param, 0, sizeof(param));
+    param.pid = 0x12;
+    param.filter.filter[0] = 0x4F;
+    param.filter.mask[0] = 0xff;
+    param.flags = DMX_CHECK_CRC;
+    if (eit & PARA_SF)
+        param.flags |= 0x100;
+    AM_TRY(AML_DMX_SetSecFilter(dmx, fid_eit_opf, &param));
+    }
 #endif
 
 #ifdef NIT_TEST
-	if(nit&0xF) {
-	AM_TRY(AML_DMX_SetBufferSize(dmx, fid_nit, 32*1024));
-	AM_TRY(AML_DMX_StartFilter(dmx, fid_nit));
-	}
+    if (nit & 0xF) {
+    memset(&param, 0, sizeof(param));
+    param.pid = 0x10;
+    param.filter.filter[0] = 0x40;
+    param.filter.mask[0] = 0xff;
+    if (nit & PARA_CRC)
+        param.flags = DMX_CHECK_CRC;
+    if (nit & PARA_SF)
+        param.flags |= 0x100;
+    AM_TRY(AML_DMX_SetSecFilter(dmx, fid_nit, &param));
+    }
 #endif
 
 #ifdef BAT_TEST
-	if(bat&0xF) {
-	AM_TRY(AML_DMX_SetBufferSize(dmx, fid_bat, 64*1024));
-	AM_TRY(AML_DMX_StartFilter(dmx, fid_bat));
-	}
+    if (bat & 0xF) {
+    memset(&param, 0, sizeof(param));
+    param.pid = 0x11;
+    param.filter.filter[0] = 0x4a;
+    param.filter.mask[0] = 0xff;
+    if (bat & PARA_CRC)
+        param.flags = DMX_CHECK_CRC;
+    if (bat & PARA_SF)
+        param.flags |= 0x100;
+    AM_TRY(AML_DMX_SetSecFilter(dmx, fid_bat, &param));
+    }
 #endif
 
-	for(i=0; i<USER_MAX; i++) {
-		if(u_pid[i]!=-1) {
-			AM_TRY(AML_DMX_AllocateFilter(dmx, &fid_user[i]));
-
-			AM_TRY(AML_DMX_SetCallback(dmx, fid_user[i], dump_bytes, (void*)(long)(i+1)));
-
-			if(u_bs[i]) {
-				AM_TRY(AML_DMX_SetBufferSize(dmx, fid_user[i], u_bs[i]));
-				printf("buffersize => %d\n", u_bs[i]);
-			}
-
-			if(get_upara(i)&UPARA_TYPE) {/*pes*/
-				printf("pes: para[%d]:%d\n", i, u_para[i]);
-				memset(&pparam, 0, sizeof(pparam));
-				pparam.pid = u_pid[i];
-				pparam.pes_type = DMX_PES_SUBTITLE;
-				pparam.input = DMX_IN_FRONTEND;
-				pparam.output = DMX_OUT_TAP;
-				if(get_upara(i)&UPARA_DMX_TAP)
-					pparam.output = DMX_OUT_TSDEMUX_TAP;
-				if(get_upara(i)&UPARA_SF)
-					pparam.flags |= 0x100;
-				AM_TRY(AML_DMX_SetPesFilter(dmx, fid_user[i], &pparam));
-
-			} else {/*sct*/
-				printf("section: para[%d]:%d\n", i, u_para[i]);
-				int v[16] = {[0 ... 15] = 0};
-				int m[16] = {[0 ... 15] = 0};
-				int ii;
-				memset(&param, 0, sizeof(param));
-				param.pid = u_pid[i];
-				if(u_ext[i]) {
-				sscanf(u_ext[i], "%x:%x,%x:%x,%x:%x,%x:%x"
-					",%x:%x,%x:%x,%x:%x,%x:%x"
-					",%x:%x,%x:%x,%x:%x,%x:%x"
-					",%x:%x,%x:%x,%x:%x,%x:%x",
-					&v[0], &m[0], &v[1], &m[1],
-					&v[2], &m[2], &v[3], &m[3],
-					&v[4], &m[4], &v[5], &m[5],
-					&v[6], &m[6], &v[7], &m[7],
-					&v[8], &m[8], &v[9], &m[9],
-					&v[10], &m[10], &v[11], &m[11],
-					&v[12], &m[12], &v[13], &m[13],
-					&v[14], &m[14], &v[15], &m[15]);
-				for(ii=0; ii<16; ii++) {
-					if(m[ii]) {
-						param.filter.filter[ii] = v[ii];
-						param.filter.mask[ii] = m[ii];
-						printf("ext%d: [%d]%x:%x\n", i, ii, v[ii], m[ii]);
-					}
-				}
-				}
-				if(get_upara(i)&UPARA_CRC)
-					param.flags = DMX_CHECK_CRC;
-				if(get_upara(i)&UPARA_SF)
-					param.flags |= 0x100;
-				AM_TRY(AML_DMX_SetSecFilter(dmx, fid_user[i], &param));
-			}
-
-			if(get_upara(i)&UPARA_FILE) {
-				char name[32];
-				sprintf(name, "%s/u_%d.dump", u_path_g, i);
-				fp[i] = fopen(name, "wb");
-				if (fp[i])
-					printf("file open:[%s]\n", name);
-				sprintf(name, "%s/u_%d.es.dump", u_path_g, i);
-				fp_e[i] = fopen(name, "wb");
-				if (fp_e[i])
-					printf("file open:[%s]\n", name);
-			}
-
-			AM_TRY(AML_DMX_StartFilter(dmx, fid_user[i]));
-		}
-	}
-
-	sleep(timeout);
 
 #ifdef PAT_TEST
-	if(pat&0xF) {
-	AM_TRY(AML_DMX_StopFilter(dmx, fid));
-	AM_TRY(AML_DMX_FreeFilter(dmx, fid));
-	}
-#endif	
+    if (pat & 0xF) {
+    AM_TRY(AML_DMX_SetBufferSize(dmx, fid, 32 * 1024));
+    AM_TRY(AML_DMX_StartFilter(dmx, fid));
+    }
+#endif
 #ifdef EIT_TEST
-	if(eit&0xF) {
-	AM_TRY(AML_DMX_StopFilter(dmx, fid_eit_pf));
-	AM_TRY(AML_DMX_FreeFilter(dmx, fid_eit_pf));
-	AM_TRY(AML_DMX_StopFilter(dmx, fid_eit_opf));
-	AM_TRY(AML_DMX_FreeFilter(dmx, fid_eit_opf));
-	}
+    if (eit & 0xF) {
+    AM_TRY(AML_DMX_SetBufferSize(dmx, fid_eit_pf, 32 * 1024));
+    AM_TRY(AML_DMX_StartFilter(dmx, fid_eit_pf));
+    AM_TRY(AML_DMX_SetBufferSize(dmx, fid_eit_opf, 32 * 1024));
+    //AM_TRY(AML_DMX_StartFilter(dmx, fid_eit_opf));
+    }
+#endif
+
+#ifdef NIT_TEST
+    if (nit & 0xF) {
+    AM_TRY(AML_DMX_SetBufferSize(dmx, fid_nit, 32 * 1024));
+    AM_TRY(AML_DMX_StartFilter(dmx, fid_nit));
+    }
+#endif
+
+#ifdef BAT_TEST
+    if (bat & 0xF) {
+    AM_TRY(AML_DMX_SetBufferSize(dmx, fid_bat, 64 * 1024));
+    AM_TRY(AML_DMX_StartFilter(dmx, fid_bat));
+    }
+#endif
+
+    for (i = 0; i < USER_MAX; i++) {
+        if (u_pid[i] != -1) {
+            AM_TRY(AML_DMX_AllocateFilter(dmx, &fid_user[i]));
+
+            AM_TRY(AML_DMX_SetCallback(dmx, fid_user[i], dump_bytes, (void*)(long)(i + 1)));
+
+            if (u_bs[i]) {
+                AM_TRY(AML_DMX_SetBufferSize(dmx, fid_user[i], u_bs[i]));
+                printf("buffersize => %d\n", u_bs[i]);
+            }
+
+            if (get_u_para(i) & PARA_TYPE) {/*pes*/
+                printf("pes: para[%d]:%d\n", i, u_para[i]);
+                memset(&pparam, 0, sizeof(pparam));
+                pparam.pid = u_pid[i];
+                pparam.pes_type = DMX_PES_SUBTITLE;
+                pparam.input = DMX_IN_FRONTEND;
+                pparam.output = DMX_OUT_TAP;
+                if (get_u_para(i) & PARA_DMX_TAP)
+                    pparam.output = DMX_OUT_TSDEMUX_TAP;
+                if (get_u_para(i) & PARA_SF)
+                    pparam.flags |= 0x100;
+                AM_TRY(AML_DMX_SetPesFilter(dmx, fid_user[i], &pparam));
+
+            } else {/*sct*/
+                printf("section: para[%d]:%d\n", i, u_para[i]);
+                int v[16] = {[0 ... 15] = 0};
+                int m[16] = {[0 ... 15] = 0};
+                int ii;
+                memset(&param, 0, sizeof(param));
+                param.pid = u_pid[i];
+                if (u_ext[i]) {
+                sscanf(u_ext[i], "%x:%x,%x:%x,%x:%x,%x:%x"
+                    ",%x:%x,%x:%x,%x:%x,%x:%x"
+                    ",%x:%x,%x:%x,%x:%x,%x:%x"
+                    ",%x:%x,%x:%x,%x:%x,%x:%x",
+                    &v[0], &m[0], &v[1], &m[1],
+                    &v[2], &m[2], &v[3], &m[3],
+                    &v[4], &m[4], &v[5], &m[5],
+                    &v[6], &m[6], &v[7], &m[7],
+                    &v[8], &m[8], &v[9], &m[9],
+                    &v[10], &m[10], &v[11], &m[11],
+                    &v[12], &m[12], &v[13], &m[13],
+                    &v[14], &m[14], &v[15], &m[15]);
+                for (ii = 0; ii < 16; ii++) {
+                    if (m[ii]) {
+                        param.filter.filter[ii] = v[ii];
+                        param.filter.mask[ii] = m[ii];
+                        printf("ext%d: [%d]%x:%x\n", i, ii, v[ii], m[ii]);
+                    }
+                }
+                }
+                if (get_u_para(i) & PARA_CRC)
+                    param.flags = DMX_CHECK_CRC;
+                if (get_u_para(i) & PARA_SF)
+                    param.flags |= 0x100;
+                AM_TRY(AML_DMX_SetSecFilter(dmx, fid_user[i], &param));
+            }
+
+            if (get_u_para(i) & PARA_FILE) {
+                char name[32];
+                sprintf(name, "%s/u_%d.dump", u_path_g, i);
+                fp[i] = fopen(name, "wb");
+                if (fp[i])
+                    printf("file open:[%s]\n", name);
+                sprintf(name, "%s/u_%d.es.dump", u_path_g, i);
+                fp_e[i] = fopen(name, "wb");
+                if (fp_e[i])
+                    printf("file open:[%s]\n", name);
+            }
+
+            AM_TRY(AML_DMX_StartFilter(dmx, fid_user[i]));
+        }
+    }
+
+    sleep(timeout);
+
+#ifdef PAT_TEST
+    if (pat & 0xF) {
+    AM_TRY(AML_DMX_StopFilter(dmx, fid));
+    AM_TRY(AML_DMX_FreeFilter(dmx, fid));
+    }
+#endif
+#ifdef EIT_TEST
+    if (eit & 0xF) {
+    AM_TRY(AML_DMX_StopFilter(dmx, fid_eit_pf));
+    AM_TRY(AML_DMX_FreeFilter(dmx, fid_eit_pf));
+    AM_TRY(AML_DMX_StopFilter(dmx, fid_eit_opf));
+    AM_TRY(AML_DMX_FreeFilter(dmx, fid_eit_opf));
+    }
 #endif
 #ifdef NIT_TEST
-	if(nit&0xF){
-	AM_TRY(AML_DMX_StopFilter(dmx, fid_nit));
-	AM_TRY(AML_DMX_FreeFilter(dmx, fid_nit));
-	}
-#endif	
+    if (nit & 0xF) {
+    AM_TRY(AML_DMX_StopFilter(dmx, fid_nit));
+    AM_TRY(AML_DMX_FreeFilter(dmx, fid_nit));
+    }
+#endif
 #ifdef BAT_TEST
-	if(bat&0xF) {
-	AM_TRY(AML_DMX_StopFilter(dmx, fid_bat));
-	AM_TRY(AML_DMX_FreeFilter(dmx, fid_bat));
-	}
-#endif	
-	
-	for(i=0; i<USER_MAX; i++) {
-		if(u_pid[i]!=-1) {
-			AM_TRY(AML_DMX_StopFilter(dmx, fid_user[i]));
-			AM_TRY(AML_DMX_FreeFilter(dmx, fid_user[i]));
-			if((get_upara(i)&UPARA_FILE) && fp[i])
-				fclose(fp[i]);
-		}
-	}
-	
-	return 0;
+    if (bat & 0xF) {
+    AM_TRY(AML_DMX_StopFilter(dmx, fid_bat));
+    AM_TRY(AML_DMX_FreeFilter(dmx, fid_bat));
+    }
+#endif
+
+    for (i = 0; i < USER_MAX; i++) {
+        if (u_pid[i] != -1) {
+            AM_TRY(AML_DMX_StopFilter(dmx, fid_user[i]));
+            AM_TRY(AML_DMX_FreeFilter(dmx, fid_user[i]));
+            if ((get_u_para(i) & PARA_FILE) && fp[i])
+                fclose(fp[i]);
+        }
+    }
+
+    return 0;
 }
 
 int get_para(char *argv)
 {
-	#define CASE(name, len, type, var) \
-		if(!strncmp(argv, name"=", (len)+1)) { \
-			sscanf(&argv[(len)+1], type, &var); \
-			printf("param["name"] => "type"\n", var); \
-		}
-	#define CASESTR(name, len, type, var) \
-		if(!strncmp(argv, name"=", (len)+1)) { \
-			var = &argv[(len)+1]; \
-			printf("param["name"] => "type"\n", var); \
-		}
+    #define CASE(name, len, type, var) \
+        if (!strncmp(argv, name"=", (len) + 1)) { \
+            sscanf(&argv[(len) + 1], type, &var); \
+            printf("param["name"] => "type"\n", var); \
+        }
+    #define CASESTR(name, len, type, var) \
+        if (!strncmp(argv, name"=", (len) + 1)) { \
+            var = &argv[(len) + 1]; \
+            printf("param["name"] => "type"\n", var); \
+        }
 
     CASE("src",  3, "%i", src)
-	else CASE("dmx",  3, "%i", dmx)
-	else CASE("pat",  3, "%x", pat)
-	else CASE("eit",  3, "%x", eit)
-	else CASE("layer",5, "%i", layer)
-	else CASE("bat",  3, "%x", bat)
-	else CASE("nit",  3, "%x", nit)
-	else CASE("timeout", 7, "%i", timeout)
-	else CASE("pall", 4, "%i", pall)
-	else CASE("pid0", 4, "%i", u_pid[0])
-	else CASE("pid1", 4, "%i", u_pid[1])
-	else CASE("pid2", 4, "%i", u_pid[2])
-	else CASE("pid3", 4, "%i", u_pid[3])
-	else CASE("pid4", 4, "%i", u_pid[4])
-	else CASE("para0", 5, "%x", u_para[0])
-	else CASE("para1", 5, "%x", u_para[1])
-	else CASE("para2", 5, "%x", u_para[2])
-	else CASE("para3", 5, "%x", u_para[3])
-	else CASE("para4", 5, "%x", u_para[4])
-	else CASESTR("ext0", 4, "%s", u_ext[0])
-	else CASESTR("ext1", 4, "%s", u_ext[1])
-	else CASESTR("ext2", 4, "%s", u_ext[2])
-	else CASESTR("ext3", 4, "%s", u_ext[3])
-	else CASESTR("ext4", 4, "%s", u_ext[4])
-	else CASE("bs0", 3, "%i", u_bs[0])
-	else CASE("bs1", 3, "%i", u_bs[1])
-	else CASE("bs2", 3, "%i", u_bs[2])
-	else CASE("bs3", 3, "%i", u_bs[3])
-	else CASE("bs4", 3, "%i", u_bs[4])
-	else CASE("para", 4, "%x", u_para_g)
-	else CASESTR("path", 4, "%s", u_path_g)
+    else CASE("dmx",  3, "%i", dmx)
+    else CASE("pat",  3, "%x", pat)
+    else CASE("eit",  3, "%x", eit)
+    else CASE("layer",5, "%i", layer)
+    else CASE("bat",  3, "%x", bat)
+    else CASE("nit",  3, "%x", nit)
+    else CASE("timeout", 7, "%i", timeout)
+    else CASE("pall", 4, "%i", pall)
+    else CASE("pid0", 4, "%i", u_pid[0])
+    else CASE("pid1", 4, "%i", u_pid[1])
+    else CASE("pid2", 4, "%i", u_pid[2])
+    else CASE("pid3", 4, "%i", u_pid[3])
+    else CASE("pid4", 4, "%i", u_pid[4])
+    else CASE("para0", 5, "%x", u_para[0])
+    else CASE("para1", 5, "%x", u_para[1])
+    else CASE("para2", 5, "%x", u_para[2])
+    else CASE("para3", 5, "%x", u_para[3])
+    else CASE("para4", 5, "%x", u_para[4])
+    else CASESTR("ext0", 4, "%s", u_ext[0])
+    else CASESTR("ext1", 4, "%s", u_ext[1])
+    else CASESTR("ext2", 4, "%s", u_ext[2])
+    else CASESTR("ext3", 4, "%s", u_ext[3])
+    else CASESTR("ext4", 4, "%s", u_ext[4])
+    else CASE("bs0", 3, "%i", u_bs[0])
+    else CASE("bs1", 3, "%i", u_bs[1])
+    else CASE("bs2", 3, "%i", u_bs[2])
+    else CASE("bs3", 3, "%i", u_bs[3])
+    else CASE("bs4", 3, "%i", u_bs[4])
+    else CASE("para", 4, "%x", u_para_g)
+    else CASESTR("path", 4, "%s", u_path_g)
 
-	if (u_path_g) {
-		char *e = strchr(u_path_g, ' ');
-		if (e) {
-			int l = e - u_path_g;
-			memcpy(u_path_g_b, u_path_g, l);
-			u_path_g_b[l] = '\0';
-			u_path_g = u_path_g_b;
-		}
-	}
+    if (u_path_g) {
+        char *e = strchr(u_path_g, ' ');
+        if (e) {
+            int l = e - u_path_g;
+            memcpy(u_path_g_b, u_path_g, l);
+            u_path_g_b[l] = '\0';
+            u_path_g = u_path_g_b;
+        }
+    }
 
-	return 0;
+    return 0;
 }
 
 int main(int argc, char **argv)
 {
-	int i;
-    int ret=0;
+    int i;
+    int ret = 0;
 
-	if (argc == 1)
-	{
-		printf(
-			"Usage:%s [src=] [dmx=] [timeout=] [pat=] [eit=] [bat=] [nit=] [pidx=] [parax=] [para=] [extx=] [bsx=]\n"
-			"  default   - src:0 dmx:0 parax:0\n"
-			"  x         - 0~4\n"
-			"  para      - d6->|111111|<-d1\n"
-			"    d1 - 0:sec 1:pes (means enable for pat/eit/bat/nit)\n"
-			"    d2 - 1:crc : sec only\n"
-			"    d3 - 1:print\n"
-			"    d4 - 1:swfilter\n"
-			"    d5 - 1:ts tap : pes only\n"
-			"    d6 - 1:w2file\n"
-			"    d7 - 1:convert pes to es format, pes only\n"
-			"  ext       - tid....\n"
-			"    eg. 0x82:0xff,0x02:0xff\n"
-			"    up to 16 filter data:mask(s)\n"
-			"  bs        - buffersize\n"
-			"  path      - output path\n",
-			argv[0]);
-		return 0;
-	}
+    if (argc == 1)
+    {
+        printf(
+            "Usage:%s [src=] [dmx=] [timeout=] [pat=] [eit=] [bat=] [nit=] [pidx=] [parax=] [para=] [extx=] [bsx=]\n"
+            "  default   - src:0 dmx:0 parax:0\n"
+            "  x         - 0~4\n"
+            "  para      - d6->|111111|<-d1\n"
+            "    d1 - 0:sec 1:pes (means enable for pat/eit/bat/nit)\n"
+            "    d2 - 1:crc : sec only\n"
+            "    d3 - 1:print\n"
+            "    d4 - 1:swfilter\n"
+            "    d5 - 1:ts tap : pes only\n"
+            "    d6 - 1:w2file\n"
+            "    d7 - 1:convert pes to es format, pes only\n"
+            "  ext       - tid....\n"
+            "    eg. 0x82:0xff,0x02:0xff\n"
+            "    up to 16 filter data:mask(s)\n"
+            "  bs        - buffersize\n"
+            "  path      - output path\n",
+            argv[0]);
+        return 0;
+    }
 
-	for (i = 1; i < argc; i++)
-		get_para(argv[i]);
+    for (i = 1; i < argc; i++)
+        get_para(argv[i]);
 
-	AM_TRY(AML_DMX_Open(dmx));
-	AM_TRY(dvb_set_demux_source(dmx, src));
-	printf("TS SRC = %d\n", src);
+    AM_TRY(AML_DMX_Open(dmx));
+    AM_TRY(dvb_set_demux_source(dmx, src));
+    printf("TS SRC = %d\n", src);
 
-	get_section(dmx, timeout);
-	AML_DMX_Close(dmx);
-	return 0;
+    get_section(dmx, timeout);
+    AML_DMX_Close(dmx);
+    return 0;
 }
diff --git a/test/am_es_test/am_es_test.c b/test/am_es_test/am_es_test.c
index 97761c9..d84ee5b 100644
--- a/test/am_es_test/am_es_test.c
+++ b/test/am_es_test/am_es_test.c
@@ -36,43 +36,43 @@
 #include <sys/time.h>
 typedef struct
 {
-	int id;
-	int rfd;
-	pthread_t thread;
-	int running;
-	int wfd;
+    int id;
+    int rfd;
+    pthread_t thread;
+    int running;
+    int wfd;
 }DVRData;
 
 static DVRData data_threads[3];
 
 static int dvr_data_write(int fd, uint8_t *buf, int size)
 {
-	int ret;
-	int left = size;
-	uint8_t *p = buf;
+    int ret;
+    int left = size;
+    uint8_t *p = buf;
 
-	while (left > 0)
-	{
-		printf("write start\n");
-		ret = write(fd, p, left);
-		printf("write end\n");
-		if (ret == -1)
-		{
-			if (errno != EINTR)
-			{
-				printf("Write DVR data failed: %s", strerror(errno));
-				break;
-			}
-			ret = 0;
-		} else {
-			printf("%s write cnt:%d\n",__FUNCTION__,ret);
-		}
+    while (left > 0)
+    {
+        printf("write start\n");
+        ret = write(fd, p, left);
+        printf("write end\n");
+        if (ret == -1)
+        {
+            if (errno != EINTR)
+            {
+                printf("Write DVR data failed: %s", strerror(errno));
+                break;
+            }
+            ret = 0;
+        } else {
+            printf("%s write cnt:%d\n",__FUNCTION__,ret);
+        }
 
-		left -= ret;
-		p += ret;
-	}
+        left -= ret;
+        p += ret;
+    }
 
-	return (size - left);
+    return (size - left);
 }
 
 
@@ -80,114 +80,114 @@
 static int inject_loop=0;
 static void* inject_entry(void *arg)
 {
-	DVRData *dvr_data = (DVRData *)arg;
-	int rfd = dvr_data->rfd;
-	int fd = dvr_data->wfd;
-	uint8_t buf[100*188];
-	int len, left=0, send, ret;
+    DVRData *dvr_data = (DVRData *)arg;
+    int rfd = dvr_data->rfd;
+    int fd = dvr_data->wfd;
+    uint8_t buf[100*188];
+    int len, left=0, send, ret;
 
-	printf("inject thread start\r\n");
-	while (inject_running) {
-			len = sizeof(buf) - left;
-			ret = read(rfd, buf+left, len);
-			if (ret == 0) {
-				break;
-			}
-			send = ret;
-			send = dvr_data_write(fd, buf, send);
-			sleep(1);
-	}
+    printf("inject thread start\r\n");
+    while (inject_running) {
+            len = sizeof(buf) - left;
+            ret = read(rfd, buf+left, len);
+            if (ret == 0) {
+                break;
+            }
+            send = ret;
+            send = dvr_data_write(fd, buf, send);
+            sleep(1);
+    }
 
-	printf("inject thread end\r\n");
-	inject_running = -1;
-	return NULL;
+    printf("inject thread end\r\n");
+    inject_running = -1;
+    return NULL;
 }
 
 int inject_file(int dvr_no, char *inject_name)
 {
-	int loop = 0;
-	int rfd;
-	char dev_name[32];
-	int fd;
-	int ret;
+    int loop = 0;
+    int rfd;
+    char dev_name[32];
+    int fd;
+    int ret;
 
-	pthread_t th;
+    pthread_t th;
 
-	printf("inject file name=%s to dvr%d\r\n", inject_name, dvr_no);
+    printf("inject file name=%s to dvr%d\r\n", inject_name, dvr_no);
 
-	snprintf(dev_name, sizeof(dev_name), "/dev/dvb0.dvr%d", dvr_no);
+    snprintf(dev_name, sizeof(dev_name), "/dev/dvb0.dvr%d", dvr_no);
 
-	fd = open(dev_name, O_WRONLY);
-	if (fd == -1)
-	{
-		printf("cannot open \"%s\" (%s)\r\n", dev_name, strerror(errno));
-		return -1;
-	}
+    fd = open(dev_name, O_WRONLY);
+    if (fd == -1)
+    {
+        printf("cannot open \"%s\" (%s)\r\n", dev_name, strerror(errno));
+        return -1;
+    }
 
-	ret = ioctl(fd, DMX_SET_INPUT, INPUT_LOCAL);
+    ret = ioctl(fd, DMX_SET_INPUT, INPUT_LOCAL);
 
-	data_threads[0].id =0;
-	data_threads[0].wfd = fd;
+    data_threads[0].id =0;
+    data_threads[0].wfd = fd;
 
-	data_threads[0].running = 0;
+    data_threads[0].running = 0;
 
-	rfd = open(inject_name, O_RDONLY, S_IRUSR);
-	if (rfd == -1) {
-		printf("cannot open \"%s\" (%s)\r\n", inject_name, strerror(errno));
-		return -1;
-	}
-	data_threads[0].rfd = rfd;
+    rfd = open(inject_name, O_RDONLY, S_IRUSR);
+    if (rfd == -1) {
+        printf("cannot open \"%s\" (%s)\r\n", inject_name, strerror(errno));
+        return -1;
+    }
+    data_threads[0].rfd = rfd;
 
-	inject_loop = loop;
-	inject_running = 1;
-	pthread_create(&th, NULL, inject_entry, (void*)(long)&data_threads[0]);
+    inject_loop = loop;
+    inject_running = 1;
+    pthread_create(&th, NULL, inject_entry, (void*)(long)&data_threads[0]);
 
-	return 0;
+    return 0;
 }
 int open_es_dmx(int dmx_no, int pid, int is_audio) {
-	char dev_name[512]={0};
-	int ret;
-	snprintf(dev_name, sizeof(dev_name), "/dev/dvb0.demux%d", dmx_no);
-	int fd = open(dev_name, O_RDWR);
-	struct dmx_pes_filter_params aparam;
-	printf("pid:%d,is audio:%d\r\n", pid, is_audio);
-	aparam.pid = pid;
-	if (is_audio) {
-		printf("pid:%d,is audio:%d set audio pes type\r\n", pid, is_audio);
-		aparam.pes_type = DMX_PES_AUDIO0;
-	}
-	else {
-		printf("pid:%d,is audio:%d set video type\r\n", pid, is_audio);
-		aparam.pes_type = DMX_PES_VIDEO0;
-	}
-	aparam.input = DMX_IN_DVR;
-	aparam.output = DMX_OUT_TAP;
-	aparam.flags = 0;
-	aparam.flags |= DMX_ES_OUTPUT;
-	if (is_audio == 0)
-	aparam.flags |= DMX_OUTPUT_RAW_MODE;
-	fcntl(fd,F_SETFL,O_NONBLOCK);
-	ret = ioctl(fd, DMX_SET_BUFFER_SIZE, 1024*1024);
-	ret = ioctl(fd, DMX_SET_PES_FILTER, &aparam);
-	ioctl(fd, DMX_START, 0);
-	if (ret == -1) {
-		printf("set pes filter failed (%s)\r\n", strerror(errno));
-		return 0;
-	}
-	return 0;
+    char dev_name[512]={0};
+    int ret;
+    snprintf(dev_name, sizeof(dev_name), "/dev/dvb0.demux%d", dmx_no);
+    int fd = open(dev_name, O_RDWR);
+    struct dmx_pes_filter_params audio_param;
+    printf("pid:%d,is audio:%d\r\n", pid, is_audio);
+    audio_param.pid = pid;
+    if (is_audio) {
+        printf("pid:%d,is audio:%d set audio pes type\r\n", pid, is_audio);
+        audio_param.pes_type = DMX_PES_AUDIO0;
+    }
+    else {
+        printf("pid:%d,is audio:%d set video type\r\n", pid, is_audio);
+        audio_param.pes_type = DMX_PES_VIDEO0;
+    }
+    audio_param.input = DMX_IN_DVR;
+    audio_param.output = DMX_OUT_TAP;
+    audio_param.flags = 0;
+    audio_param.flags |= DMX_ES_OUTPUT;
+    if (is_audio == 0)
+    audio_param.flags |= DMX_OUTPUT_RAW_MODE;
+    fcntl(fd,F_SETFL,O_NONBLOCK);
+    ret = ioctl(fd, DMX_SET_BUFFER_SIZE, 1024*1024);
+    ret = ioctl(fd, DMX_SET_PES_FILTER, &audio_param);
+    ioctl(fd, DMX_START, 0);
+    if (ret == -1) {
+        printf("set pes filter failed (%s)\r\n", strerror(errno));
+        return 0;
+    }
+    return 0;
 }
 int main(int argc, char **argv)
 {
-	printf("argc:%d,%s  %s \r\n", argc, argv[0], argv[1]);
-	if (argc < 4) {
-		printf("usage:\r\n");
-		printf("am_es_test pid isaudio filepath\r\n");
-		return 0;
-	}
-	open_es_dmx(0, atoi(argv[1]),atoi(argv[2]));
-	inject_file(0,argv[3]);
-	printf("start sleep 20s\r\n");
-	sleep(20);
-	printf("exit\r\n");
-	return 0;
+    printf("argc:%d,%s  %s \r\n", argc, argv[0], argv[1]);
+    if (argc < 4) {
+        printf("usage:\r\n");
+        printf("am_es_test pid isaudio filepath\r\n");
+        return 0;
+    }
+    open_es_dmx(0, atoi(argv[1]),atoi(argv[2]));
+    inject_file(0,argv[3]);
+    printf("start sleep 20s\r\n");
+    sleep(20);
+    printf("exit\r\n");
+    return 0;
 }
\ No newline at end of file
diff --git a/test/am_fend_test/am_fend_test.c b/test/am_fend_test/am_fend_test.c
index beaa572..15d60b6 100644
--- a/test/am_fend_test/am_fend_test.c
+++ b/test/am_fend_test/am_fend_test.c
@@ -18,7 +18,7 @@
   * \li mode: tune mode
   * \li freq: frequency MHz
   * \li sym_rate: symbol_rate
-  * \li modul: modulation
+  * \li module: modulation
   * \li bw: bandwidth
   * \li tran_mode: transmission_mode
   * \li plp: plp_id, only for dvb-t2
@@ -58,11 +58,11 @@
   *
   * Lock DVB-C:
   * \code
-  *   am_fend_test [fe=fontend_idx] [mode=1] [freq=frequency] [sym_rate=symbol_rate] [modul=modulation] [timer=check_tune_time]
+  *   am_fend_test [fe=fontend_idx] [mode=1] [freq=frequency] [sym_rate=symbol_rate] [module=modulation] [timer=check_tune_time]
   * \endcode
   * Lock DVB-T:
   * \code
-  *   am_fend_test [fe=fontend_idx] [mode=2] [freq=frequency] [bw=bandwidth] [tran_mode=transmission_mode]	[timer=check_tune_time]
+  *   am_fend_test [fe=fontend_idx] [mode=2] [freq=frequency] [bw=bandwidth] [tran_mode=transmission_mode]    [timer=check_tune_time]
   * \endcode
   * Lock DVB-T2:
   * \code
@@ -70,11 +70,11 @@
   * \endcode
   * Lock DVB-S:
   * \code
-  *   am_fend_test [fe=fontend_idx] [mode=4] [freq=frequency] [sym_rate=symbol_rate] [modul=modulation] [timer=check_tune_time]
+  *   am_fend_test [fe=fontend_idx] [mode=4] [freq=frequency] [sym_rate=symbol_rate] [module=modulation] [timer=check_tune_time]
   * \endcode
   * Lock DVB-S2:
   * \code
-  *   am_fend_test [fe=fontend_idx] [mode=5] [freq=frequency] [sym_rate=symbol_rate] [modul=modulation] [timer=check_tune_time]
+  *   am_fend_test [fe=fontend_idx] [mode=5] [freq=frequency] [sym_rate=symbol_rate] [module=modulation] [timer=check_tune_time]
   * \endcode
   * Lock DTMB:
   * \code
@@ -110,7 +110,7 @@
 #include "frontend.h"
 #include "dvb_frontend_wrapper.h"
 
-#define TUNE_MODE_UNKNOW 0
+#define TUNE_MODE_UNKNOWN 0
 #define TUNE_MODE_DVB_C 1
 #define TUNE_MODE_DVB_T 2
 #define TUNE_MODE_DVB_T2 3
@@ -157,14 +157,14 @@
 
 static void usage(int argc, char *argv[])
 {
-  printf("[Lock DVB-C:] \n%s fe=fontend_idx mode=1 freq=frequency sym_rate=symbol_rate modul=modulation timer=check_tune_time\n", argv[0]);
+  printf("[Lock DVB-C:] \n%s fe=fontend_idx mode=1 freq=frequency sym_rate=symbol_rate module=modulation timer=check_tune_time\n", argv[0]);
   printf("[Lock DVB-T:] \n%s fe=fontend_idx mode=2 freq=frequency bw=bandwidth tran_mode=transmission_mode timer=check_tune_time\n", argv[0]);
   printf("[Lock DVB-T2:]\n%s fe=fontend_idx mode=3 freq=frequency bw=bandwidth  tran_mode=transmission_mode  plp=plp_id timer=check_tune_time\n", argv[0]);
-  printf("[Lock DVB-S:] \n%s fe=fontend_idx mode=4 freq=frequency sym_rate=symbol_rate modul=modulation timer=check_tune_time\n", argv[0]);
-  printf("[Lock DVB-S2:]\n%s fe=fontend_idx mode=5 freq=frequency sym_rate=symbol_rate modul=modulation timer=check_tune_time\n", argv[0]);
+  printf("[Lock DVB-S:] \n%s fe=fontend_idx mode=4 freq=frequency sym_rate=symbol_rate module=modulation timer=check_tune_time\n", argv[0]);
+  printf("[Lock DVB-S2:]\n%s fe=fontend_idx mode=5 freq=frequency sym_rate=symbol_rate module=modulation timer=check_tune_time\n", argv[0]);
   printf("[Lock DTMB:]\n%s fe=fontend_idx mode=6 freq=frequency bw=bandwidth timer=check_tune_time\n", argv[0]);
 
-  printf("\nfreq(MHZ) lo(MHz) timer(second)\n");
+  printf("\n""freq(MHZ) lo(MHz) timer(second)\n");
   printf("mode:%s\n", help_mode);
   printf("modulation:%s\n", help_modulation);
   printf("bw:%s\n", help_bandwidth);
@@ -175,17 +175,17 @@
 {
   int i;
   int ret = -1;
-  int check_tune_time;
-  int mode = TUNE_MODE_UNKNOW;
+  int check_tune_time = 0;
+  int mode = TUNE_MODE_UNKNOWN;
   int fontend_id = INVALID_FD;
   int fontend_idx = 0;
-  int frequency; //MHz
+  int frequency = 0; //MHz
   //DVB-C
-  int symbol_rate;
-  int modulation;
+  int symbol_rate = 0;
+  int modulation = 0;
   //DVB-T
-  int bandwidth;
-  int transmission_mode;
+  int bandwidth = 0;
+  int transmission_mode = 0;
   int guard_interval;
   int plp_id = 0;
   //DVB-S
@@ -205,8 +205,8 @@
       sscanf(argv[i], "freq=%i", &frequency);
     else if (!strncmp(argv[i], "sym_rate", 8))
       sscanf(argv[i], "sym_rate=%i", &symbol_rate);
-    else if (!strncmp(argv[i], "modul", 5))
-      sscanf(argv[i], "modul=%i", &modulation);
+    else if (!strncmp(argv[i], "module", 5))
+      sscanf(argv[i], "module=%i", &modulation);
     else if (!strncmp(argv[i], "bw", 2))
       sscanf(argv[i], "bw=%i", &bandwidth);
     else if (!strncmp(argv[i], "tran_mode", 9))
@@ -293,9 +293,9 @@
     ret = AML_FE_TuneDVB_T(fontend_id, &terrestrial);
     printf("DTMB: lock to freq:%d, bandwidth:%d ret:%d \n", frequency, bandwidth, ret);
     break;
-  case TUNE_MODE_UNKNOW:
+  case TUNE_MODE_UNKNOWN:
   default:
-    printf("tune mode unknow, mode:%d", mode);
+    printf("tune mode unknown, mode:%d", mode);
     break;
   }
 
@@ -307,14 +307,14 @@
 
   int num = (check_tune_time > 0 ? check_tune_time : 60);
   printf("Will check tune status %ds\n", num);
-  dmd_tuner_event_t revent = TUNER_STATE_UNKNOW;
+  dmd_tuner_event_t event = TUNER_STATE_UNKNOWN;
   while (num--)
   {
     sleep(1);
-    revent = AML_FE_GetTuneStatus(fontend_id);
-    printf("####### [%s] #######\n", revent == TUNER_STATE_LOCKED ? "LOCKED" : "UNLOCKED");
+    event = AML_FE_GetTuneStatus(fontend_id);
+    printf("####### [%s] #######\n", event == TUNER_STATE_LOCKED ? "LOCKED" : "UNLOCKED");
   }
 
-  AML_FE_Colse(fontend_id);
+  AML_FE_Close(fontend_id);
   return 0;
 }
diff --git a/test/am_rawci_test/Android.bp b/test/am_rawci_test/Android.bp
new file mode 100644
index 0000000..a3d3075
--- /dev/null
+++ b/test/am_rawci_test/Android.bp
@@ -0,0 +1,29 @@
+
+cc_binary {
+    name: "am_rawci_test",
+    proprietary: true,
+    compile_multilib: "32",
+
+    arch: {
+        x86: {
+            enabled: false,
+        },
+        x86_64: {
+            enabled: false,
+        },
+    },
+
+    srcs: [
+        "am_rawci_test.c"
+    ],
+
+    shared_libs: [
+        "libutils",
+        "libcutils",
+        "liblog"
+    ],
+
+    include_dirs: [
+    ],
+
+}
diff --git a/test/am_rawci_test/Android.mk1 b/test/am_rawci_test/Android.mk1
new file mode 100644
index 0000000..e2f49a7
--- /dev/null
+++ b/test/am_rawci_test/Android.mk1
@@ -0,0 +1,17 @@
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES:= dvr_write_test.c
+
+LOCAL_MODULE:= dvr_write_test
+
+LOCAL_MODULE_TAGS := optional
+LOCAL_C_INCLUDES :=  $(LOCAL_PATH)/../../include/
+#LOCAL_MULTILIB := 32
+
+LOCAL_CFLAGS+=-DANDROID -DAMLINUX
+
+LOCAL_SHARED_LIBRARIES := liblog libc
+
+include $(BUILD_EXECUTABLE)
diff --git a/test/am_rawci_test/am_rawci_test.c b/test/am_rawci_test/am_rawci_test.c
new file mode 100644
index 0000000..96acc14
--- /dev/null
+++ b/test/am_rawci_test/am_rawci_test.c
@@ -0,0 +1,266 @@
+#include <sys/types.h>
+#include <sys/ioctl.h>
+#include <sys/prctl.h>
+
+#include <poll.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <pthread.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "../../include/dvb_utils.h"
+#include "../../include/amci.h"
+
+typedef struct
+{
+    int dev_no;
+    int running;
+    pthread_t thread;
+    pthread_mutex_t lock;
+    int   fd;
+
+}dvb_ci_t;
+
+#define CI_COUNT 1
+
+static dvb_ci_t CI_devices[CI_COUNT];
+
+DVB_RESULT AM_CI_Detect(int dev_no, int *dec);
+
+static inline DVB_RESULT ci_get_dev(int dev_no, dvb_ci_t **dev)
+{
+    if ((dev_no < 0) || (dev_no >= CI_COUNT))
+    {
+        DVB_DEBUG("invalid CI device number %d, must in(%d~%d)", dev_no, 0, CI_COUNT-1);
+        return DVB_FAILURE;
+    }
+
+    *dev = &CI_devices[dev_no];
+    return DVB_SUCCESS;
+}
+
+static void* ci_data_thread(void *arg)
+{
+    dvb_ci_t *dev = NULL;
+    if (ci_get_dev(0, &dev))
+    {
+        DVB_DEBUG("Wrong dmx device no %d", 0);
+        return NULL;
+    }
+    int dec = 0;
+    // coverity[loop_condition]
+    while (dev->running)
+    {
+        AM_CI_Detect(0, &dec);
+        usleep(2000*2000);
+    }
+    return NULL;
+}
+
+
+DVB_RESULT AM_CI_Open(int dev_no)
+{
+    dvb_ci_t *dev = NULL;
+
+    if (ci_get_dev(dev_no, &dev))
+    {
+        DVB_DEBUG("Wrong dmx device no %d", dev_no);
+        return DVB_FAILURE;
+    }
+    char dev_name[32];
+    if (dev->running)
+    {
+        DVB_DEBUG("CI DEV already initialized");
+        return DVB_FAILURE;
+    }
+
+    dev->dev_no = dev_no;
+
+    pthread_mutex_init(&dev->lock, NULL);
+    dev->running = 1;
+    memset(dev_name, 0, sizeof(dev_name));
+    sprintf(dev_name, "%s", "/dev/rawci");
+    dev->fd = open(dev_name, O_RDWR);
+    if (dev->fd == -1)
+    {
+        DVB_DEBUG("cannot open \"%s\" (%s)", dev_name, strerror(errno));
+        return DVB_FAILURE;
+    }
+    pthread_create(&dev->thread, NULL, ci_data_thread, dev);
+
+    return DVB_SUCCESS;
+}
+
+DVB_RESULT AM_CI_Detect(int dev_no, int *dec)
+{
+    dvb_ci_t *dev = NULL;
+
+    if (ci_get_dev(dev_no, &dev))
+    {
+        DVB_DEBUG("Wrong ci device no %d", dev_no);
+        return DVB_FAILURE;
+    }
+    int detect = 0;
+    if (dev->fd < 0) {
+        DVB_DEBUG("Wrong ci device no %d", dev_no);
+        return DVB_FAILURE;
+    }
+
+    if (ioctl(dev->fd, AMCI_IOC_GET_DETECT, &detect) < 0) {
+        DVB_DEBUG("get detect info errot ci device no %d", dev_no);
+        return DVB_FAILURE;
+    }
+    DVB_DEBUG("detect info ci device no %d, detect[%d]", dev_no, detect);
+    *dec = detect;
+    return DVB_SUCCESS;
+}
+
+DVB_RESULT AM_CI_Power(int dev_no, int power)
+{
+    dvb_ci_t *dev = NULL;
+
+    if (ci_get_dev(dev_no, &dev))
+    {
+        DVB_DEBUG("Wrong ci device no %d", dev_no);
+        return DVB_FAILURE;
+    }
+    int detect = 0;
+    if (dev->fd < 0) {
+        DVB_DEBUG("Wrong ci device no %d", dev_no);
+        return DVB_FAILURE;
+    }
+
+    if (ioctl(dev->fd, AMCI_IOC_SET_POWER, &power) < 0) {
+        DVB_DEBUG("set power error ci device no %d", dev_no);
+        return DVB_FAILURE;
+    }
+    DVB_DEBUG("set ci device no %d, power[%d]", dev_no, power);
+    return DVB_SUCCESS;
+}
+
+DVB_RESULT AM_CI_Reset(int dev_no)
+{
+    dvb_ci_t *dev = NULL;
+
+    if (ci_get_dev(dev_no, &dev))
+    {
+        DVB_DEBUG("Wrong ci device no %d", dev_no);
+        return DVB_FAILURE;
+    }
+    int detect = 0;
+    if (dev->fd < 0) {
+        DVB_DEBUG("Wrong ci device no %d", dev_no);
+        return DVB_FAILURE;
+    }
+
+    if (ioctl(dev->fd, AMCI_IOC_RESET, 0) < 0) {
+        DVB_DEBUG("set reset error ci device no %d", dev_no);
+        return DVB_FAILURE;
+    }
+    DVB_DEBUG("reset ci device no %d", dev_no);
+    return DVB_SUCCESS;
+}
+
+u_int8_t AM_CI_Ior(int dev_no, int addr)
+{
+    dvb_ci_t *dev = NULL;
+    struct ci_rw_param param;
+
+    if (ci_get_dev(dev_no, &dev))
+    {
+        DVB_DEBUG("Wrong ci device no %d", dev_no);
+        return DVB_FAILURE;
+    }
+    if (dev->fd < 0) {
+        DVB_DEBUG("Wrong ci device no %d", dev_no);
+        return DVB_FAILURE;
+    }
+    param.mode = AM_CI_IOR;
+    param.addr = addr;
+    //param.value ; return value
+    if (ioctl(dev->fd, AMCI_IOC_IO, &param) < 0) {
+        DVB_DEBUG("IOR error ci device no %d", dev_no);
+        return DVB_FAILURE;
+    }
+    return param.value;
+}
+
+DVB_RESULT AM_CI_Iow(int dev_no, int addr, uint8_t value)
+{
+    dvb_ci_t *dev = NULL;
+    struct ci_rw_param param;
+
+    if (ci_get_dev(dev_no, &dev))
+    {
+        DVB_DEBUG("Wrong ci device no %d", dev_no);
+        return DVB_FAILURE;
+    }
+    if (dev->fd < 0) {
+        DVB_DEBUG("Wrong ci device no %d", dev_no);
+        return DVB_FAILURE;
+    }
+    param.mode = AM_CI_IOW;
+    param.addr = addr;
+    param.value = value;//
+    if (ioctl(dev->fd, AMCI_IOC_IO, &param) < 0) {
+        DVB_DEBUG("IOW error ci device no %d", dev_no);
+        return DVB_FAILURE;
+    }
+    return DVB_SUCCESS;
+}
+
+
+u_int8_t AM_CI_Memr(int dev_no, int addr)
+{
+    dvb_ci_t *dev = NULL;
+    struct ci_rw_param param;
+
+    if (ci_get_dev(dev_no, &dev))
+    {
+        DVB_DEBUG("Wrong ci device no %d", dev_no);
+        return DVB_FAILURE;
+    }
+    if (dev->fd < 0) {
+        DVB_DEBUG("Wrong ci device no %d", dev_no);
+        return DVB_FAILURE;
+    }
+    param.mode = AM_CI_MEMR;
+    param.addr = addr;
+    //param.value ; return value
+    if (ioctl(dev->fd, AMCI_IOC_IO, &param) < 0) {
+        DVB_DEBUG("MEMR error ci device no %d", dev_no);
+        return DVB_FAILURE;
+    }
+    return param.value;
+}
+
+DVB_RESULT AM_CI_Memw(int dev_no, int addr, uint8_t value)
+{
+    dvb_ci_t *dev = NULL;
+    struct ci_rw_param param;
+
+    if (ci_get_dev(dev_no, &dev))
+    {
+        DVB_DEBUG("Wrong ci device no %d", dev_no);
+        return DVB_FAILURE;
+    }
+    if (dev->fd < 0) {
+        DVB_DEBUG("Wrong ci device no %d", dev_no);
+        return DVB_FAILURE;
+    }
+    param.mode = AM_CI_MEMW;
+    param.addr = addr;
+    param.value = value;//
+    if (ioctl(dev->fd, AMCI_IOC_IO, &param) < 0) {
+        DVB_DEBUG("MEMW error ci device no %d", dev_no);
+        return DVB_FAILURE;
+    }
+    return DVB_SUCCESS;
+}
+
+int main(int argc, char **argv)
+{
+    return 0;
+}
diff --git a/test/am_smc_test/Android.mk1 b/test/am_smc_test/Android.mk1
index a42485e..d16a410 100644
--- a/test/am_smc_test/Android.mk1
+++ b/test/am_smc_test/Android.mk1
@@ -13,7 +13,7 @@
 
 LOCAL_CFLAGS+=-DANDROID -DAMLINUX -DCHIP_8226M -DLINUX_DVB_FEND
 #LOCAL_C_INCLUDES :=  $(LOCAL_PATH)/../../android/ndk/include
-				
+                
 LOCAL_SHARED_LIBRARIES :=  libc
 
 include $(BUILD_EXECUTABLE)
diff --git a/test/am_smc_test/Makefile b/test/am_smc_test/Makefile
index eda22a8..d8ad3e8 100644
--- a/test/am_smc_test/Makefile
+++ b/test/am_smc_test/Makefile
@@ -14,10 +14,10 @@
 all : $(OBJS) $(OUTPUT)
 
 $(OBJS) : %.o : %.c
-	$(CC) $(CFLAGS) -c $< -o $@
+    $(CC) $(CFLAGS) -c $< -o $@
 
 $(OUTPUT) : $(OBJS)
-	$(CC) $(LDFLAGS) -o $@ $^
+    $(CC) $(LDFLAGS) -o $@ $^
 
 clean:
-	@rm -f $(OBJS)
+    @rm -f $(OBJS)
diff --git a/test/am_smc_test/am_evt.c b/test/am_smc_test/am_evt.c
index 3c9dac2..1788a9a 100644
--- a/test/am_smc_test/am_evt.c
+++ b/test/am_smc_test/am_evt.c
@@ -34,11 +34,11 @@
 typedef struct AM_Event AM_Event_t;
 struct AM_Event
 {
-	AM_Event_t        *next;    /**< 指向链表中的下一个事件*/
-	AM_EVT_Callback_t  cb;      /**< 回调函数*/
-	int                type;    /**< 事件类型*/
-	int                dev_no;  /**< 设备号*/
-	void              *data;    /**< 用户回调参数*/
+    AM_Event_t        *next;    /**< 指向链表中的下一个事件*/
+    AM_EVT_Callback_t  cb;      /**< 回调函数*/
+    int                type;    /**< 事件类型*/
+    int                dev_no;  /**< 设备号*/
+    void              *data;    /**< 用户回调参数*/
 };
 
 /****************************************************************************
@@ -71,35 +71,35 @@
  */
 AM_ErrorCode_t AM_EVT_Subscribe(int dev_no, int event_type, AM_EVT_Callback_t cb, void *data)
 {
-	AM_Event_t *evt;
-	int pos;
-	
-	assert(cb);
-	
-	/*分配事件*/
-	evt = malloc(sizeof(AM_Event_t));
-	if(!evt)
-	{
-		printf("not enough memory");
-		return AM_EVT_ERR_NO_MEM;
-	}
-	
-	evt->dev_no = dev_no;
-	evt->type   = event_type;
-	evt->cb     = cb;
-	evt->data   = data;
-	
-	pos = event_type%AM_EVT_BUCKET_COUNT;
-	
-	/*加入事件哈希表中*/
-	pthread_mutex_lock(&lock);
-	
-	evt->next   = events[pos];
-	events[pos] = evt;
-	
-	pthread_mutex_unlock(&lock);
-	
-	return AM_SUCCESS;
+    AM_Event_t *evt;
+    int pos;
+
+    assert(cb);
+
+    /*分配事件*/
+    evt = malloc(sizeof(AM_Event_t));
+    if (!evt)
+    {
+        printf("not enough memory");
+        return AM_EVT_ERR_NO_MEM;
+    }
+
+    evt->dev_no = dev_no;
+    evt->type   = event_type;
+    evt->cb     = cb;
+    evt->data   = data;
+
+    pos = event_type%AM_EVT_BUCKET_COUNT;
+
+    /*加入事件哈希表中*/
+    pthread_mutex_lock(&lock);
+
+    evt->next   = events[pos];
+    events[pos] = evt;
+
+    pthread_mutex_unlock(&lock);
+
+    return AM_SUCCESS;
 }
 
 /**\brief 反注册一个事件回调函数
@@ -113,37 +113,37 @@
  */
 AM_ErrorCode_t AM_EVT_Unsubscribe(int dev_no, int event_type, AM_EVT_Callback_t cb, void *data)
 {
-	AM_Event_t *evt, *eprev;
-	int pos;
-	
-	assert(cb);
-	
-	pos = event_type%AM_EVT_BUCKET_COUNT;
-	
-	pthread_mutex_lock(&lock);
-	
-	for(eprev=NULL,evt=events[pos]; evt; eprev=evt,evt=evt->next)
-	{
-		if((evt->dev_no==dev_no) && (evt->type==event_type) && (evt->cb==cb) &&
-				(evt->data==data))
-		{
-			if(eprev)
-				eprev->next = evt->next;
-			else
-				events[pos] = evt->next;
-			break;
-		}
-	}
-	
-	pthread_mutex_unlock(&lock);
-	
-	if(evt)
-	{
-		free(evt);
-		return AM_SUCCESS;
-	}
-	
-	return AM_EVT_ERR_NOT_SUBSCRIBED;
+    AM_Event_t *evt, *eprev;
+    int pos;
+
+    assert(cb);
+
+    pos = event_type%AM_EVT_BUCKET_COUNT;
+
+    pthread_mutex_lock(&lock);
+
+    for (eprev = NULL, evt = events[pos]; evt; eprev = evt,evt = evt->next)
+    {
+        if ((evt->dev_no == dev_no) && (evt->type == event_type) && (evt->cb == cb) &&
+                (evt->data == data))
+        {
+            if (eprev)
+                eprev->next = evt->next;
+            else
+                events[pos] = evt->next;
+            break;
+        }
+    }
+
+    pthread_mutex_unlock(&lock);
+
+    if (evt)
+    {
+        free(evt);
+        return AM_SUCCESS;
+    }
+
+    return AM_EVT_ERR_NOT_SUBSCRIBED;
 }
 
 /**\brief 触发一个事件
@@ -153,21 +153,21 @@
  */
 AM_ErrorCode_t AM_EVT_Signal(int dev_no, int event_type, void *param)
 {
-	AM_Event_t *evt;
-	int pos = event_type%AM_EVT_BUCKET_COUNT;
-	
-	pthread_mutex_lock(&lock);
-	
-	for(evt=events[pos]; evt; evt=evt->next)
-	{
-		if((evt->dev_no==dev_no) && (evt->type==event_type))
-		{
-			evt->cb(dev_no, event_type, param, evt->data);
-		}
-	}
-	
-	pthread_mutex_unlock(&lock);
-	
-	return AM_SUCCESS;
+    AM_Event_t *evt;
+    int pos = event_type%AM_EVT_BUCKET_COUNT;
+
+    pthread_mutex_lock(&lock);
+
+    for (evt = events[pos]; evt; evt = evt->next)
+    {
+        if ((evt->dev_no == dev_no) && (evt->type == event_type))
+        {
+            evt->cb(dev_no, event_type, param, evt->data);
+        }
+    }
+
+    pthread_mutex_unlock(&lock);
+
+    return AM_SUCCESS;
 }
 
diff --git a/test/am_smc_test/am_evt.h b/test/am_smc_test/am_evt.h
index de1fa35..bc70868 100644
--- a/test/am_smc_test/am_evt.h
+++ b/test/am_smc_test/am_evt.h
@@ -32,10 +32,10 @@
 /**\brief 事件模块错误代码*/
 enum AM_EVT_ErrorCode
 {
-	AM_EVT_ERROR_BASE=AM_ERROR_BASE(AM_MOD_EVT),
-	AM_EVT_ERR_NO_MEM,                  /**< 空闲内存不足*/
-	AM_EVT_ERR_NOT_SUBSCRIBED,          /**< 事件还没有注册*/
-	AM_EVT_ERR_END
+    AM_EVT_ERROR_BASE=AM_ERROR_BASE(AM_MOD_EVT),
+    AM_EVT_ERR_NO_MEM,                  /**< 空闲内存不足*/
+    AM_EVT_ERR_NOT_SUBSCRIBED,          /**< 事件还没有注册*/
+    AM_EVT_ERR_END
 };
 
 /****************************************************************************
@@ -46,7 +46,7 @@
 typedef void (*AM_EVT_Callback_t)(int dev_no, int event_type, void *param, void *data);
 
 /****************************************************************************
- * Function prototypes  
+ * Function prototypes
  ***************************************************************************/
 
 /**\brief 注册一个事件回调函数
diff --git a/test/am_smc_test/am_mem.h b/test/am_smc_test/am_mem.h
index c79f903..fd05a0d 100644
--- a/test/am_smc_test/am_mem.h
+++ b/test/am_smc_test/am_mem.h
@@ -37,47 +37,47 @@
 
 /**\brief 内存缓冲区分配*/
 #define AM_MEM_Alloc(_size) \
-	({\
-	void *_ptr = malloc(_size);\
-	if (!_ptr) {\
-		AM_MEM_ERROR_DEBUG(_size);\
-	}\
-	_ptr;\
-	})
+    ({\
+    void *_ptr = malloc(_size);\
+    if (!_ptr) {\
+        AM_MEM_ERROR_DEBUG(_size);\
+    }\
+    _ptr;\
+    })
 
 /**\brief 重新设定缓冲区大小*/
 #define AM_MEM_Realloc(_old,_size) \
-	({\
-	void *_ptr=realloc(_old,_size);\
-	if (!_ptr) {\
-		AM_MEM_ERROR_DEBUG(_size);\
-	}\
-	_ptr;\
-	})
+    ({\
+    void *_ptr=realloc(_old,_size);\
+    if (!_ptr) {\
+        AM_MEM_ERROR_DEBUG(_size);\
+    }\
+    _ptr;\
+    })
 
 /**\brief 内存缓冲区释放*/
 #define AM_MEM_Free(_ptr) \
-	AM_MACRO_BEGIN\
-	if (_ptr) free(_ptr);\
-	AM_MACRO_END
+    AM_MACRO_BEGIN\
+    if (_ptr) free(_ptr);\
+    AM_MACRO_END
 
 /**\brief 分配内存并复制字符串*/
 #define AM_MEM_Strdup(_str) \
-	({\
-	void *_ptr = strdup(_str);\
-	if (!_ptr) {\
-		AM_MEM_ERROR_DEBUG(strlen(_str));\
-	}\
-	_ptr;\
-	})
+    ({\
+    void *_ptr = strdup(_str);\
+    if (!_ptr) {\
+        AM_MEM_ERROR_DEBUG(strlen(_str));\
+    }\
+    _ptr;\
+    })
 
 /**\brief 分配内存并将缓冲区清0*/
 #define AM_MEM_Alloc0(_size) \
-	({\
-	void *_ptr = AM_MEM_Alloc((_size));\
-	if(_ptr) memset(_ptr, 0, (_size));\
-	_ptr;\
-	})
+    ({\
+    void *_ptr = AM_MEM_Alloc((_size));\
+    if(_ptr) memset(_ptr, 0, (_size));\
+    _ptr;\
+    })
 
 /**\brief 根据类型_type的大小分配内存*/
 #define AM_MEM_ALLOC_TYPE(_type)       AM_MEM_Alloc(sizeof(_type))
@@ -93,11 +93,11 @@
 
 /**\brief 从内存池分配一个缓冲区并清0*/
 #define AM_MEM_PoolAlloc0(_pool,_size) \
-	({\
-	void *_ptr = AM_MEM_PoolAlloc(_pool,_size);\
-	if(_ptr) memset(_ptr, 0, _size);\
-	_ptr;\
-	})
+    ({\
+    void *_ptr = AM_MEM_PoolAlloc(_pool,_size);\
+    if(_ptr) memset(_ptr, 0, _size);\
+    _ptr;\
+    })
 
 /**\brief 根据类型_type的大小从内存池分配内存*/
 #define AM_MEM_POOL_ALLOC_TYPE(_pool,_type)       AM_MEM_PoolAlloc(_pool,sizeof(_type))
@@ -121,12 +121,12 @@
  */
 typedef struct
 {
-	int        pool_size;   /**< 每次分配的内存大小*/
-	void      *pools;       /**< 内存块链表*/
+    int        pool_size;   /**< 每次分配的内存大小*/
+    void      *pools;       /**< 内存块链表*/
 } AM_MEM_Pool_t;
 
 /****************************************************************************
- * Function prototypes  
+ * Function prototypes
  ***************************************************************************/
 
 /**\brief 初始化一个缓冲池
diff --git a/test/am_smc_test/am_sc2_smc_test.c b/test/am_smc_test/am_sc2_smc_test.c
index cd06b71..436042d 100644
--- a/test/am_smc_test/am_sc2_smc_test.c
+++ b/test/am_smc_test/am_sc2_smc_test.c
@@ -21,80 +21,80 @@
 
 static void smc_cb(int dev_no, AM_SMC_CardStatus_t status, void *data)
 {
-	if(status==AM_SMC_CARD_IN)
-	{
-		printf("cb: card in!\n");
-	}
-	else
-	{
-		printf("cb: card out!\n");
-	}
+    if (status == AM_SMC_CARD_IN)
+    {
+        printf("cb: card in!\n");
+    }
+    else
+    {
+        printf("cb: card out!\n");
+    }
 }
 
 static int smc_test(AM_Bool_t sync)
 {
-	AM_SMC_OpenPara_t para;
-	uint8_t atr[AM_SMC_MAX_ATR_LEN];
-	int i, len;
-	AM_SMC_CardStatus_t status;
-//	uint8_t sbuf[5]={0x80, 0x44, 0x00, 0x00, 0x08};
-	uint8_t sbuf[5]={0xD0, 0x58, 0x00, 0x00, 0x4A};
-	uint8_t rbuf[256];
-	int rlen = sizeof(rbuf);
-	
-	memset(&para, 0, sizeof(para));
-	para.enable_thread = !sync;
-	AM_TRY(AM_SMC_Open(SMC_DEV_NO, &para));
-	
-	if(!sync)
-	{
-		AM_SMC_SetCallback(SMC_DEV_NO, smc_cb, NULL);
-	}
-	
-	printf("please insert a card\n");
-	do {
-		AM_TRY(AM_SMC_GetCardStatus(SMC_DEV_NO, &status));
-		usleep(100000);
-	} while(status==AM_SMC_CARD_OUT);
-	
-	printf("card in\n");
-	
-	len = sizeof(atr);
-	AM_TRY(AM_SMC_Reset(SMC_DEV_NO, atr, &len));
-	printf("ATR: ");
-	for(i=0; i<len; i++)
-	{
-		printf("%02x ", atr[i]);
-	}
-	printf("\n");
-#if 0	
-	AM_TRY(AM_SMC_TransferT0(SMC_DEV_NO, sbuf, sizeof(sbuf), rbuf, &rlen));
-	printf("send: ");
-	for(i=0; i<sizeof(sbuf); i++)
-	{
-		printf("%02x ", sbuf[i]);
-	}
-	printf("\n");
-	
-	printf("recv: ");
-	for(i=0; i<rlen; i++)
-	{
-		printf("%02x ", rbuf[i]);
-	}
-	printf("\n");
-#endif	
-	AM_TRY(AM_SMC_Close(SMC_DEV_NO));
-	
-	return 0;
+    AM_SMC_OpenPara_t para;
+    uint8_t atr[AM_SMC_MAX_ATR_LEN] = {0};
+    int i, len;
+    AM_SMC_CardStatus_t status = AM_SMC_CARD_OUT;
+//    uint8_t sbuf[5]={0x80, 0x44, 0x00, 0x00, 0x08};
+    uint8_t sbuf[5] = {0xD0, 0x58, 0x00, 0x00, 0x4A};
+    uint8_t rbuf[256];
+    int rlen = sizeof(rbuf);
+
+    memset(&para, 0, sizeof(para));
+    para.enable_thread = !sync;
+    AM_TRY(AM_SMC_Open(SMC_DEV_NO, &para));
+
+    if (!sync)
+    {
+        AM_SMC_SetCallback(SMC_DEV_NO, smc_cb, NULL);
+    }
+
+    printf("please insert a card\n");
+    do {
+        AM_TRY(AM_SMC_GetCardStatus(SMC_DEV_NO, &status));
+        usleep(100000);
+    } while (status == AM_SMC_CARD_OUT);
+
+    printf("card in\n");
+
+    len = sizeof(atr);
+    AM_TRY(AM_SMC_Reset(SMC_DEV_NO, atr, &len));
+    printf("ATR: ");
+    for (i = 0; i < len; i++)
+    {
+        printf("%02x ", atr[i]);
+    }
+    printf("\n");
+#if 0
+    AM_TRY(AM_SMC_TransferT0(SMC_DEV_NO, sbuf, sizeof(sbuf), rbuf, &rlen));
+    printf("send: ");
+    for (i = 0; i < sizeof(sbuf); i++)
+    {
+        printf("%02x ", sbuf[i]);
+    }
+    printf("\n");
+
+    printf("recv: ");
+    for (i = 0; i < rlen; i++)
+    {
+        printf("%02x ", rbuf[i]);
+    }
+    printf("\n");
+#endif
+    AM_TRY(AM_SMC_Close(SMC_DEV_NO));
+
+    return 0;
 }
 
 int main(int argc, char **argv)
 {
-	printf("sync mode test\n");
-	smc_test(AM_TRUE);
-	
-//	printf("async mode test\n");
-//	smc_test(AM_FALSE);
-	return 0;
+    printf("sync mode test\n");
+    smc_test(AM_TRUE);
+
+//    printf("async mode test\n");
+//    smc_test(AM_FALSE);
+    return 0;
 }
 
diff --git a/test/am_smc_test/am_smc.c b/test/am_smc_test/am_smc.c
index 4743eff..7f35eef 100644
--- a/test/am_smc_test/am_smc.c
+++ b/test/am_smc_test/am_smc.c
@@ -56,183 +56,183 @@
 /**\brief 根据设备号取得设备结构*/
 static AM_INLINE AM_ErrorCode_t smc_get_dev(int dev_no, AM_SMC_Device_t **dev)
 {
-	if((dev_no<0) || (dev_no>=SMC_DEV_COUNT))
-	{
-		printf( "invalid smartcard device number %d, must in(%d~%d)", dev_no, 0, SMC_DEV_COUNT-1);
-		return AM_SMC_ERR_INVALID_DEV_NO;
-	}
-	
-	*dev = &smc_devices[dev_no];
-	return AM_SUCCESS;
+    if ((dev_no < 0) || (dev_no >= SMC_DEV_COUNT))
+    {
+        printf( "invalid smartcard device number %d, must in(%d~%d)", dev_no, 0, SMC_DEV_COUNT-1);
+        return AM_SMC_ERR_INVALID_DEV_NO;
+    }
+
+    *dev = &smc_devices[dev_no];
+    return AM_SUCCESS;
 }
 
 /**\brief 根据设备号取得设备结构并检查设备是否已经打开*/
 static AM_INLINE AM_ErrorCode_t smc_get_openned_dev(int dev_no, AM_SMC_Device_t **dev)
 {
-	AM_TRY(smc_get_dev(dev_no, dev));
-	
-	if(!(*dev)->openned)
-	{
-		printf( "smartcard device %d has not been openned", dev_no);
-		return AM_SMC_ERR_NOT_OPENNED;
-	}
-	
-	return AM_SUCCESS;
+    AM_TRY(smc_get_dev(dev_no, dev));
+
+    if (!(*dev)->openned)
+    {
+        printf( "smartcard device %d has not been openned", dev_no);
+        return AM_SMC_ERR_NOT_OPENNED;
+    }
+
+    return AM_SUCCESS;
 }
 
 /**\brief 从智能卡读取数据*/
 static AM_ErrorCode_t smc_read(AM_SMC_Device_t *dev, uint8_t *buf, int len, int *act_len, int timeout)
 {
-	uint8_t *ptr = buf;
-	int left = len;
-	int now, end = 0, diff, cnt = 0;
-	AM_ErrorCode_t ret = AM_SUCCESS;
-	
-	if(timeout>=0)
-	{
-		AM_TIME_GetClock(&now);
-		end = now + timeout;
-	}
-	
-	while (left)
-	{
-		int tlen = left;
-		int ms;
-		
-		if(timeout>=0)
-		{
-			ms = end-now;
-		}
-		else
-		{
-			ms = -1;
-		}
-		
-		ret = dev->drv->read(dev, ptr, &tlen, ms);
-		
-		if(ret<0)
-		{
-			break;
-		}
-		
-		ptr  += tlen;
-		left -= tlen;
-		cnt  += tlen;
-		
-		AM_TIME_GetClock(&now);
-		diff = now-end;
-		if(diff>=0)
-		{
-			printf( "read %d bytes timeout", len);
-			ret = AM_SMC_ERR_TIMEOUT;
-			break;
-		}
-	}
-	
-	if(act_len)
-		*act_len = cnt;
+    uint8_t *ptr = buf;
+    int left = len;
+    int now, end = 0, diff, cnt = 0;
+    AM_ErrorCode_t ret = AM_SUCCESS;
 
-	return ret;
+    if (timeout >= 0)
+    {
+        AM_TIME_GetClock(&now);
+        end = now + timeout;
+    }
+
+    while (left)
+    {
+        int tlen = left;
+        int ms;
+
+        if (timeout >= 0)
+        {
+            ms = end-now;
+        }
+        else
+        {
+            ms = -1;
+        }
+
+        ret = dev->drv->read(dev, ptr, &tlen, ms);
+
+        if (ret < 0)
+        {
+            break;
+        }
+
+        ptr  += tlen;
+        left -= tlen;
+        cnt  += tlen;
+
+        AM_TIME_GetClock(&now);
+        diff = now - end;
+        if (diff >= 0)
+        {
+            printf( "read %d bytes timeout", len);
+            ret = AM_SMC_ERR_TIMEOUT;
+            break;
+        }
+    }
+
+    if (act_len)
+        *act_len = cnt;
+
+    return ret;
 }
 
 /**\brief 向智能卡发送数据*/
 static AM_ErrorCode_t smc_write(AM_SMC_Device_t *dev, const uint8_t *buf, int len, int *act_len, int timeout)
 {
-	const uint8_t *ptr = buf;
-	int left = len;
-	int now, end = 0, diff, cnt = 0;
-	AM_ErrorCode_t ret = AM_SUCCESS;
-	
-	if(timeout>=0)
-	{
-		AM_TIME_GetClock(&now);
-		end = now + timeout;
-	}
-	
-	while (left)
-	{
-		int tlen = left;
-		int ms;
-		
-		if(timeout>=0)
-		{
-			ms = end-now;
-		}
-		else
-		{
-			ms = -1;
-		}
-		
-		ret = dev->drv->write(dev, ptr, &tlen, ms);
-		
-		if(ret<0)
-		{
-			break;
-		}
-		
-		ptr  += tlen;
-		left -= tlen;
-		cnt  += tlen;
-		
-		AM_TIME_GetClock(&now);
-		diff = now-end;
-		if(diff>=0)
-		{
-			printf( "write %d bytes timeout", len);
-			ret = AM_SMC_ERR_TIMEOUT;
-			break;
-		}
-	}
-	
-	if(act_len)
-		*act_len = cnt;
+    const uint8_t *ptr = buf;
+    int left = len;
+    int now, end = 0, diff, cnt = 0;
+    AM_ErrorCode_t ret = AM_SUCCESS;
 
-	return ret;
+    if (timeout >= 0)
+    {
+        AM_TIME_GetClock(&now);
+        end = now + timeout;
+    }
+
+    while (left)
+    {
+        int tlen = left;
+        int ms;
+
+        if (timeout >= 0)
+        {
+            ms = end-now;
+        }
+        else
+        {
+            ms = -1;
+        }
+
+        ret = dev->drv->write(dev, ptr, &tlen, ms);
+
+        if (ret < 0)
+        {
+            break;
+        }
+
+        ptr  += tlen;
+        left -= tlen;
+        cnt  += tlen;
+
+        AM_TIME_GetClock(&now);
+        diff = now-end;
+        if (diff >= 0)
+        {
+            printf( "write %d bytes timeout", len);
+            ret = AM_SMC_ERR_TIMEOUT;
+            break;
+        }
+    }
+
+    if (act_len)
+        *act_len = cnt;
+
+    return ret;
 }
 
 /**\brief status monitor thread*/
 static void*
 smc_status_thread(void *arg)
 {
-	AM_SMC_Device_t *dev = (AM_SMC_Device_t*)arg;
-	AM_SMC_CardStatus_t old_status = AM_SMC_CARD_OUT;
-	
-	while(dev->enable_thread)
-	{
-		AM_SMC_CardStatus_t status;
-		AM_ErrorCode_t ret;
-		
-		pthread_mutex_lock(&dev->lock);
-		
-		ret = dev->drv->get_status(dev, &status);
-		
-		pthread_mutex_unlock(&dev->lock);
-		
-		if(status!=old_status)
-		{
-			old_status = status;
-			
-			pthread_mutex_lock(&dev->lock);
-			dev->flags |= SMC_FL_RUN_CB;
-			pthread_mutex_unlock(&dev->lock);
-			
-			if(dev->cb)
-			{
-				dev->cb(dev->dev_no, status, dev->user_data);
-			}
-			
-			AM_EVT_Signal(dev->dev_no, (status==AM_SMC_CARD_OUT)?AM_SMC_EVT_CARD_OUT:AM_SMC_EVT_CARD_IN, NULL);
-			
-			pthread_mutex_lock(&dev->lock);
-			dev->flags &= ~SMC_FL_RUN_CB;
-			pthread_mutex_unlock(&dev->lock);
-			pthread_cond_broadcast(&dev->cond);
-		}
+    AM_SMC_Device_t *dev = (AM_SMC_Device_t*)arg;
+    AM_SMC_CardStatus_t old_status = AM_SMC_CARD_OUT;
 
-		usleep(SMC_STATUS_SLEEP_TIME*1000);
-	}
-	
-	return NULL;
+    while (dev->enable_thread)
+    {
+        AM_SMC_CardStatus_t status = AM_SMC_CARD_OUT;
+        AM_ErrorCode_t ret;
+
+        pthread_mutex_lock(&dev->lock);
+
+        ret = dev->drv->get_status(dev, &status);
+
+        pthread_mutex_unlock(&dev->lock);
+
+        if (status != old_status)
+        {
+            old_status = status;
+
+            pthread_mutex_lock(&dev->lock);
+            dev->flags |= SMC_FL_RUN_CB;
+            pthread_mutex_unlock(&dev->lock);
+
+            if (dev->cb)
+            {
+                dev->cb(dev->dev_no, status, dev->user_data);
+            }
+
+            AM_EVT_Signal(dev->dev_no, (status==AM_SMC_CARD_OUT)?AM_SMC_EVT_CARD_OUT:AM_SMC_EVT_CARD_IN, NULL);
+
+            pthread_mutex_lock(&dev->lock);
+            dev->flags &= ~SMC_FL_RUN_CB;
+            pthread_mutex_unlock(&dev->lock);
+            pthread_cond_broadcast(&dev->cond);
+        }
+
+        usleep(SMC_STATUS_SLEEP_TIME*1000);
+    }
+
+    return NULL;
 }
 
 /****************************************************************************
@@ -248,59 +248,61 @@
  */
 AM_ErrorCode_t AM_SMC_Open(int dev_no, const AM_SMC_OpenPara_t *para)
 {
-	AM_SMC_Device_t *dev;
-	AM_ErrorCode_t ret = AM_SUCCESS;
-	
-	assert(para);
-	
-	AM_TRY(smc_get_dev(dev_no, &dev));
-	
-//	pthread_mutex_lock(&am_gAdpLock);
-	
-	if(dev->openned)
-	{
-		printf( "smartcard device %d has already been openned", dev_no);
-		ret = AM_SMC_ERR_BUSY;
-		goto final;
-	}
-	
-	dev->dev_no = dev_no;
-	
-	if(dev->drv->open)
-	{
-		AM_TRY_FINAL(dev->drv->open(dev, para));
-	}
-	
-	pthread_mutex_init(&dev->lock, NULL);
-	pthread_cond_init(&dev->cond, NULL);
-	
-	dev->enable_thread = para->enable_thread;
-	dev->openned = AM_TRUE;
-	dev->flags = 0;
-	
-	if(dev->enable_thread)
-	{
-		if(pthread_create(&dev->status_thread, NULL, smc_status_thread, dev))
-		{
-			printf( "cannot create the status monitor thread");
-			pthread_mutex_destroy(&dev->lock);
-			pthread_cond_destroy(&dev->cond);
-			if(dev->drv->close)
-			{
-				dev->drv->close(dev);
-			}
-			ret = AM_SMC_ERR_CANNOT_CREATE_THREAD;
-			goto final;
-		}
-	}
-	else
-	{
-		dev->status_thread = (pthread_t)-1;
-	}
+    AM_SMC_Device_t *dev;
+    AM_ErrorCode_t ret = AM_SUCCESS;
+
+    assert(para);
+
+    AM_TRY(smc_get_dev(dev_no, &dev));
+
+//    pthread_mutex_lock(&am_gAdpLock);
+
+    if (dev->openned)
+    {
+        printf( "smartcard device %d has already been openned", dev_no);
+        ret = AM_SMC_ERR_BUSY;
+        goto final;
+    }
+
+    dev->dev_no = dev_no;
+
+    if (dev->drv->open)
+    {
+        AM_TRY_FINAL(dev->drv->open(dev, para));
+    }
+
+    pthread_mutex_init(&dev->lock, NULL);
+    pthread_cond_init(&dev->cond, NULL);
+
+    dev->enable_thread = para->enable_thread;
+    dev->openned = AM_TRUE;
+    pthread_mutex_lock(&dev->lock);
+    dev->flags = 0;
+    pthread_mutex_unlock(&dev->lock);
+
+    if (dev->enable_thread)
+    {
+        if (pthread_create(&dev->status_thread, NULL, smc_status_thread, dev))
+        {
+            printf( "cannot create the status monitor thread");
+            pthread_mutex_destroy(&dev->lock);
+            pthread_cond_destroy(&dev->cond);
+            if (dev->drv->close)
+            {
+                dev->drv->close(dev);
+            }
+            ret = AM_SMC_ERR_CANNOT_CREATE_THREAD;
+            goto final;
+        }
+    }
+    else
+    {
+        dev->status_thread = (pthread_t)-1;
+    }
 final:
-//	pthread_mutex_unlock(&am_gAdpLock);
-	
-	return ret;
+//    pthread_mutex_unlock(&am_gAdpLock);
+
+    return ret;
 }
 
 /**\brief 关闭智能卡设备
@@ -311,31 +313,31 @@
  */
 AM_ErrorCode_t AM_SMC_Close(int dev_no)
 {
-	AM_SMC_Device_t *dev;
-	
-	AM_TRY(smc_get_openned_dev(dev_no, &dev));
-	
-//	pthread_mutex_lock(&am_gAdpLock);
-	
-	if(dev->enable_thread)
-	{
-		dev->enable_thread = AM_FALSE;
-		pthread_join(dev->status_thread, NULL);
-	}
-	
-	if(dev->drv->close)
-	{
-		dev->drv->close(dev);
-	}
-	
-	pthread_mutex_destroy(&dev->lock);
-	pthread_cond_destroy(&dev->cond);
-	
-	dev->openned = AM_FALSE;
-	
-//	pthread_mutex_unlock(&am_gAdpLock);
-	
-	return AM_SUCCESS;
+    AM_SMC_Device_t *dev;
+
+    AM_TRY(smc_get_openned_dev(dev_no, &dev));
+
+//    pthread_mutex_lock(&am_gAdpLock);
+
+    if (dev->enable_thread)
+    {
+        dev->enable_thread = AM_FALSE;
+        pthread_join(dev->status_thread, NULL);
+    }
+
+    if (dev->drv->close)
+    {
+        dev->drv->close(dev);
+    }
+
+    pthread_mutex_destroy(&dev->lock);
+    pthread_cond_destroy(&dev->cond);
+
+    dev->openned = AM_FALSE;
+
+//    pthread_mutex_unlock(&am_gAdpLock);
+
+    return AM_SUCCESS;
 }
 
 /**\brief 得到当前的智能卡插入状态
@@ -347,27 +349,27 @@
  */
 AM_ErrorCode_t AM_SMC_GetCardStatus(int dev_no, AM_SMC_CardStatus_t *status)
 {
-	AM_SMC_Device_t *dev;
-	AM_ErrorCode_t ret = AM_SUCCESS;
-	
-	assert(status);
-	
-	AM_TRY(smc_get_openned_dev(dev_no, &dev));
-	
-	if(!dev->drv->get_status)
-	{
-		printf( "driver do not support get_status");
-		ret = AM_SMC_ERR_NOT_SUPPORTED;
-	}
-	
-	if(ret==0)
-	{
-		pthread_mutex_lock(&dev->lock);
-		ret = dev->drv->get_status(dev, status);
-		pthread_mutex_unlock(&dev->lock);
-	}
-	
-	return ret;
+    AM_SMC_Device_t *dev;
+    AM_ErrorCode_t ret = AM_SUCCESS;
+
+    assert(status);
+
+    AM_TRY(smc_get_openned_dev(dev_no, &dev));
+
+    if (!dev->drv->get_status)
+    {
+        printf( "driver do not support get_status");
+        ret = AM_SMC_ERR_NOT_SUPPORTED;
+    }
+
+    if (ret == 0)
+    {
+        pthread_mutex_lock(&dev->lock);
+        ret = dev->drv->get_status(dev, status);
+        pthread_mutex_unlock(&dev->lock);
+    }
+
+    return ret;
 }
 
 /**\brief 复位智能卡
@@ -380,43 +382,43 @@
  */
 AM_ErrorCode_t AM_SMC_Reset(int dev_no, uint8_t *atr, int *len)
 {
-	AM_SMC_Device_t *dev;
-	AM_ErrorCode_t ret = AM_SUCCESS;
-	uint8_t atr_buf[AM_SMC_MAX_ATR_LEN];
-	int len_buf;
-	
-	if(atr && len)
-	{
-		if(*len<AM_SMC_MAX_ATR_LEN)
-		{
-			printf( "ATR buffer < %d", AM_SMC_MAX_ATR_LEN);
-			return AM_SMC_ERR_BUF_TOO_SMALL;
-		}
-	}
-	else
-	{
-		if(!atr)
-			atr = atr_buf;
-		if(!len)
-			len = &len_buf;
-	}
-	
-	AM_TRY(smc_get_openned_dev(dev_no, &dev));
-	
-	if(!dev->drv->reset)
-	{
-		printf( "driver do not support reset");
-		ret = AM_SMC_ERR_NOT_SUPPORTED;
-	}
-	
-	if(ret==0)
-	{
-		pthread_mutex_lock(&dev->lock);
-		ret = dev->drv->reset(dev, atr, len);
-		pthread_mutex_unlock(&dev->lock);
-	}
-	
-	return ret;
+    AM_SMC_Device_t *dev;
+    AM_ErrorCode_t ret = AM_SUCCESS;
+    uint8_t atr_buf[AM_SMC_MAX_ATR_LEN];
+    int len_buf;
+
+    if (atr && len)
+    {
+        if (*len < AM_SMC_MAX_ATR_LEN)
+        {
+            printf( "ATR buffer < %d", AM_SMC_MAX_ATR_LEN);
+            return AM_SMC_ERR_BUF_TOO_SMALL;
+        }
+    }
+    else
+    {
+        if (!atr)
+            atr = atr_buf;
+        if (!len)
+            len = &len_buf;
+    }
+
+    AM_TRY(smc_get_openned_dev(dev_no, &dev));
+
+    if (!dev->drv->reset)
+    {
+        printf( "driver do not support reset");
+        ret = AM_SMC_ERR_NOT_SUPPORTED;
+    }
+
+    if (ret == 0)
+    {
+        pthread_mutex_lock(&dev->lock);
+        ret = dev->drv->reset(dev, atr, len);
+        pthread_mutex_unlock(&dev->lock);
+    }
+
+    return ret;
 }
 
 /**\brief 从智能卡读取数据
@@ -431,20 +433,20 @@
  */
 AM_ErrorCode_t AM_SMC_Read(int dev_no, uint8_t *data, int len, int timeout)
 {
-	AM_SMC_Device_t *dev;
-	AM_ErrorCode_t ret = AM_SUCCESS;
-	
-	assert(data);
-	
-	AM_TRY(smc_get_openned_dev(dev_no, &dev));
-	
-	pthread_mutex_lock(&dev->lock);
-	
-	ret = smc_read(dev, data, len, NULL, timeout);
-	
-	pthread_mutex_unlock(&dev->lock);
-	
-	return ret;
+    AM_SMC_Device_t *dev;
+    AM_ErrorCode_t ret = AM_SUCCESS;
+
+    assert(data);
+
+    AM_TRY(smc_get_openned_dev(dev_no, &dev));
+
+    pthread_mutex_lock(&dev->lock);
+
+    ret = smc_read(dev, data, len, NULL, timeout);
+
+    pthread_mutex_unlock(&dev->lock);
+
+    return ret;
 }
 
 /**\brief 向智能卡发送数据
@@ -459,20 +461,20 @@
  */
 AM_ErrorCode_t AM_SMC_Write(int dev_no, const uint8_t *data, int len, int timeout)
 {
-	AM_SMC_Device_t *dev;
-	AM_ErrorCode_t ret = AM_SUCCESS;
-	
-	assert(data);
-	
-	AM_TRY(smc_get_openned_dev(dev_no, &dev));
-	
-	pthread_mutex_lock(&dev->lock);
-	
-	ret = smc_write(dev, data, len, NULL, timeout);
-	
-	pthread_mutex_unlock(&dev->lock);
-	
-	return ret;
+    AM_SMC_Device_t *dev;
+    AM_ErrorCode_t ret = AM_SUCCESS;
+
+    assert(data);
+
+    AM_TRY(smc_get_openned_dev(dev_no, &dev));
+
+    pthread_mutex_lock(&dev->lock);
+
+    ret = smc_write(dev, data, len, NULL, timeout);
+
+    pthread_mutex_unlock(&dev->lock);
+
+    return ret;
 }
 
 /**\brief 从智能卡读取数据
@@ -488,24 +490,24 @@
 AM_ErrorCode_t
 AM_SMC_ReadEx(int dev_no, uint8_t *data, int len, int timeout)
 {
-	AM_SMC_Device_t *dev;
-	AM_ErrorCode_t ret = AM_SUCCESS;
-	int act_len;
-	
-	assert(data);
-	
-	AM_TRY(smc_get_openned_dev(dev_no, &dev));
-	
-	pthread_mutex_lock(&dev->lock);
-	
-	ret = smc_read(dev, data, len, &act_len, timeout);
-	
-	pthread_mutex_unlock(&dev->lock);
+    AM_SMC_Device_t *dev;
+    AM_ErrorCode_t ret = AM_SUCCESS;
+    int act_len;
 
-	if((ret >= 0) || (ret == AM_SMC_ERR_TIMEOUT))
-		return act_len;
-	
-	return ret;
+    assert(data);
+
+    AM_TRY(smc_get_openned_dev(dev_no, &dev));
+
+    pthread_mutex_lock(&dev->lock);
+
+    ret = smc_read(dev, data, len, &act_len, timeout);
+
+    pthread_mutex_unlock(&dev->lock);
+
+    if ((ret >= 0) || (ret == AM_SMC_ERR_TIMEOUT))
+        return act_len;
+
+    return ret;
 
 }
 
@@ -522,24 +524,24 @@
 AM_ErrorCode_t
 AM_SMC_WriteEx(int dev_no, const uint8_t *data, int len, int timeout)
 {
-	AM_SMC_Device_t *dev;
-	AM_ErrorCode_t ret = AM_SUCCESS;
-	int act_len;
-	
-	assert(data);
-	
-	AM_TRY(smc_get_openned_dev(dev_no, &dev));
-	
-	pthread_mutex_lock(&dev->lock);
-	
-	ret = smc_write(dev, data, len, &act_len, timeout);
-	
-	pthread_mutex_unlock(&dev->lock);
+    AM_SMC_Device_t *dev;
+    AM_ErrorCode_t ret = AM_SUCCESS;
+    int act_len;
 
-	if((ret >= 0) || (ret == AM_SMC_ERR_TIMEOUT))
-		return act_len;
-	
-	return ret;
+    assert(data);
+
+    AM_TRY(smc_get_openned_dev(dev_no, &dev));
+
+    pthread_mutex_lock(&dev->lock);
+
+    ret = smc_write(dev, data, len, &act_len, timeout);
+
+    pthread_mutex_unlock(&dev->lock);
+
+    if ((ret >= 0) || (ret == AM_SMC_ERR_TIMEOUT))
+        return act_len;
+
+    return ret;
 }
 
 /**\brief 按T0协议传输数据
@@ -554,92 +556,91 @@
  */
 AM_ErrorCode_t AM_SMC_TransferT0(int dev_no, const uint8_t *send, int slen, uint8_t *recv, int *rlen)
 {
-	AM_SMC_Device_t *dev;
-	AM_ErrorCode_t ret = AM_SUCCESS;
-	uint8_t byte;
-	uint8_t *dst;
-	int left;
-	AM_Bool_t sent = AM_FALSE;
-	
-	assert(send && recv && rlen && (slen>=5));
-	
-	dst  = recv;
-	left = *rlen;
-	
-	AM_TRY(smc_get_openned_dev(dev_no, &dev));
-	
-	pthread_mutex_lock(&dev->lock);
-	
-	AM_TRY_FINAL(smc_write(dev, send, 5, NULL, 1000));
-	
-	while(1)
-	{
-		AM_TRY_FINAL(smc_read(dev, &byte, 1, NULL, 1000));
-		if(byte==0x60)
-		{
-			continue;
-		}
-		else if(((byte&0xF0)==0x60) || ((byte&0xF0)==0x90))
-		{
-			if(left<2)
-			{
-				printf( "receive buffer must >= %d", 2);
-				ret = AM_SMC_ERR_BUF_TOO_SMALL;
-				goto final;
-			}
-			dst[0] = byte;
-			AM_TRY_FINAL(smc_read(dev, &dst[1], 1, NULL, 1000));
-			dst += 2;
-			left -= 2;
-			break;
-		}
-		else if(byte==send[1])
-		{
-			if(!sent)
-			{
-				int cnt = slen - 5;
-			
-				if(cnt)
-				{
-					AM_TRY_FINAL(smc_write(dev, send+5, cnt, NULL, 5000));
-				}
-				else
-				{
-					cnt = send[4];
-					if(!cnt) cnt = 256;
-					
-					if(left<cnt+2)
-					{
-						printf( "receive buffer must >= %d", cnt+2);
-						ret = AM_SMC_ERR_BUF_TOO_SMALL;
-						goto final;
-					}
-					
-					AM_TRY_FINAL(smc_read(dev, dst, cnt, NULL, 5000));
-					dst  += cnt;
-					left -= cnt;
-				}
-				
-				sent = AM_TRUE;
-			}
-			else
-			{
-				ret = AM_SMC_ERR_IO;
-				break;
-			}
-		}
-		else
-		{
-			ret = AM_SMC_ERR_IO;
-			break;
-		}
-	}
+    AM_SMC_Device_t *dev = NULL;
+    AM_ErrorCode_t ret = AM_SUCCESS;
+    uint8_t byte = 0;
+    uint8_t *dst = NULL;
+    int left = 0;
+    AM_Bool_t sent = AM_FALSE;
+
+    assert(send && recv && rlen && (slen >= 5));
+
+    dst  = recv;
+    left = *rlen;
+
+    AM_TRY(smc_get_openned_dev(dev_no, &dev));
+
+    pthread_mutex_lock(&dev->lock);
+
+    AM_TRY_FINAL(smc_write(dev, send, 5, NULL, 1000));
+
+    while (1)
+    {
+        AM_TRY_FINAL(smc_read(dev, &byte, 1, NULL, 1000));
+        if (byte == 0x60)
+        {
+            continue;
+        }
+        if (((byte & 0xF0) == 0x60) || ((byte & 0xF0) == 0x90))
+        {
+            if (left < 2)
+            {
+                printf( "receive buffer must >= %d", 2);
+                ret = AM_SMC_ERR_BUF_TOO_SMALL;
+                goto final;
+            }
+            dst[0] = byte;
+            AM_TRY_FINAL(smc_read(dev, &dst[1], 1, NULL, 1000));
+            dst += 2;
+            break;
+        }
+        else if (byte == send[1])
+        {
+            if (!sent)
+            {
+                int cnt = slen - 5;
+
+                if (cnt)
+                {
+                    AM_TRY_FINAL(smc_write(dev, send + 5, cnt, NULL, 5000));
+                }
+                else
+                {
+                    cnt = send[4];
+                    if (!cnt) cnt = 256;
+
+                    if (left < cnt + 2)
+                    {
+                        printf( "receive buffer must >= %d", cnt+2);
+                        ret = AM_SMC_ERR_BUF_TOO_SMALL;
+                        goto final;
+                    }
+
+                    AM_TRY_FINAL(smc_read(dev, dst, cnt, NULL, 5000));
+                    dst  += cnt;
+                    left -= cnt;
+                }
+
+                sent = AM_TRUE;
+            }
+            else
+            {
+                ret = AM_SMC_ERR_IO;
+                break;
+            }
+        }
+        else
+        {
+            ret = AM_SMC_ERR_IO;
+            break;
+        }
+    }
 final:
-	pthread_mutex_unlock(&dev->lock);
-	
-	*rlen = dst-recv;
-	
-	return ret;
+    pthread_mutex_unlock(&dev->lock);
+
+    *rlen = dst-recv;
+
+    return ret;
 }
 
 /**\brief 取得当前的智能卡状态回调函数
@@ -652,26 +653,26 @@
  */
 AM_ErrorCode_t AM_SMC_GetCallback(int dev_no, AM_SMC_StatusCb_t *cb, void **data)
 {
-	AM_SMC_Device_t *dev;
-	AM_ErrorCode_t ret = AM_SUCCESS;
-	
-	AM_TRY(smc_get_openned_dev(dev_no, &dev));
-	
-	pthread_mutex_lock(&dev->lock);
-	
-	if(cb)
-	{
-		*cb = dev->cb;
-	}
-	
-	if(data)
-	{
-		*data = dev->user_data;
-	}
-	
-	pthread_mutex_unlock(&dev->lock);
-	
-	return ret;
+    AM_SMC_Device_t *dev;
+    AM_ErrorCode_t ret = AM_SUCCESS;
+
+    AM_TRY(smc_get_openned_dev(dev_no, &dev));
+
+    pthread_mutex_lock(&dev->lock);
+
+    if (cb)
+    {
+        *cb = dev->cb;
+    }
+
+    if (data)
+    {
+        *data = dev->user_data;
+    }
+
+    pthread_mutex_unlock(&dev->lock);
+
+    return ret;
 }
 
 /**\brief 设定智能卡状态回调函数
@@ -684,24 +685,24 @@
  */
 AM_ErrorCode_t AM_SMC_SetCallback(int dev_no, AM_SMC_StatusCb_t cb, void *data)
 {
-	AM_SMC_Device_t *dev;
-	AM_ErrorCode_t ret = AM_SUCCESS;
-	
-	AM_TRY(smc_get_openned_dev(dev_no, &dev));
-	
-	pthread_mutex_lock(&dev->lock);
-	
-	while((dev->flags&SMC_FL_RUN_CB) && (pthread_self()!=dev->status_thread))
-	{
-		pthread_cond_wait(&dev->cond, &dev->lock);
-	}
-	
-	dev->cb = cb;
-	dev->user_data = data;
-	
-	pthread_mutex_unlock(&dev->lock);
-	
-	return ret;
+    AM_SMC_Device_t *dev;
+    AM_ErrorCode_t ret = AM_SUCCESS;
+
+    AM_TRY(smc_get_openned_dev(dev_no, &dev));
+
+    pthread_mutex_lock(&dev->lock);
+
+    while ((dev->flags & SMC_FL_RUN_CB) && (pthread_self() != dev->status_thread))
+    {
+        pthread_cond_wait(&dev->cond, &dev->lock);
+    }
+
+    dev->cb = cb;
+    dev->user_data = data;
+
+    pthread_mutex_unlock(&dev->lock);
+
+    return ret;
 }
 
 /**\brief 激活智能卡设备
@@ -712,25 +713,25 @@
  */
 AM_ErrorCode_t AM_SMC_Active(int dev_no)
 {
-	AM_SMC_Device_t *dev;
-	AM_ErrorCode_t ret = AM_SUCCESS;
-	
-	AM_TRY(smc_get_openned_dev(dev_no, &dev));
-	
-	if(!dev->drv->active)
-	{
-		printf( "driver do not support active");
-		ret = AM_SMC_ERR_NOT_SUPPORTED;
-	}
-	
-	if(ret==0)
-	{
-		pthread_mutex_lock(&dev->lock);
-		ret = dev->drv->active(dev);
-		pthread_mutex_unlock(&dev->lock);
-	}
-	
-	return ret;
+    AM_SMC_Device_t *dev;
+    AM_ErrorCode_t ret = AM_SUCCESS;
+
+    AM_TRY(smc_get_openned_dev(dev_no, &dev));
+
+    if (!dev->drv->active)
+    {
+        printf( "driver do not support active");
+        ret = AM_SMC_ERR_NOT_SUPPORTED;
+    }
+
+    if (ret == 0)
+    {
+        pthread_mutex_lock(&dev->lock);
+        ret = dev->drv->active(dev);
+        pthread_mutex_unlock(&dev->lock);
+    }
+
+    return ret;
 }
 
 /**\brief 取消激活智能卡设备
@@ -741,25 +742,25 @@
  */
 AM_ErrorCode_t AM_SMC_Deactive(int dev_no)
 {
-	AM_SMC_Device_t *dev;
-	AM_ErrorCode_t ret = AM_SUCCESS;
-	
-	AM_TRY(smc_get_openned_dev(dev_no, &dev));
-	
-	if(!dev->drv->deactive)
-	{
-		printf( "driver do not support deactive");
-		ret = AM_SMC_ERR_NOT_SUPPORTED;
-	}
-	
-	if(ret==0)
-	{
-		pthread_mutex_lock(&dev->lock);
-		ret = dev->drv->deactive(dev);
-		pthread_mutex_unlock(&dev->lock);
-	}
-	
-	return ret;
+    AM_SMC_Device_t *dev;
+    AM_ErrorCode_t ret = AM_SUCCESS;
+
+    AM_TRY(smc_get_openned_dev(dev_no, &dev));
+
+    if (!dev->drv->deactive)
+    {
+        printf( "driver do not support deactive");
+        ret = AM_SMC_ERR_NOT_SUPPORTED;
+    }
+
+    if (ret == 0)
+    {
+        pthread_mutex_lock(&dev->lock);
+        ret = dev->drv->deactive(dev);
+        pthread_mutex_unlock(&dev->lock);
+    }
+
+    return ret;
 }
 
 /**\brief 获取智能卡参数
@@ -771,27 +772,27 @@
  */
 AM_ErrorCode_t AM_SMC_GetParam(int dev_no, AM_SMC_Param_t *para)
 {
-	AM_SMC_Device_t *dev;
-	AM_ErrorCode_t ret = AM_SUCCESS;
-	
-	assert(para);
-	
-	AM_TRY(smc_get_openned_dev(dev_no, &dev));
-	
-	if(!dev->drv->get_param)
-	{
-		printf( "driver do not support get_param");
-		ret = AM_SMC_ERR_NOT_SUPPORTED;
-	}
-	
-	if(ret==0)
-	{
-		pthread_mutex_lock(&dev->lock);
-		ret = dev->drv->get_param(dev, para);
-		pthread_mutex_unlock(&dev->lock);
-	}
-	
-	return ret;
+    AM_SMC_Device_t *dev;
+    AM_ErrorCode_t ret = AM_SUCCESS;
+
+    assert(para);
+
+    AM_TRY(smc_get_openned_dev(dev_no, &dev));
+
+    if (!dev->drv->get_param)
+    {
+        printf( "driver do not support get_param");
+        ret = AM_SMC_ERR_NOT_SUPPORTED;
+    }
+
+    if (ret == 0)
+    {
+        pthread_mutex_lock(&dev->lock);
+        ret = dev->drv->get_param(dev, para);
+        pthread_mutex_unlock(&dev->lock);
+    }
+
+    return ret;
 }
 
 /**\brief 设定智能卡参数
@@ -803,26 +804,26 @@
  */
 AM_ErrorCode_t AM_SMC_SetParam(int dev_no, const AM_SMC_Param_t *para)
 {
-	AM_SMC_Device_t *dev;
-	AM_ErrorCode_t ret = AM_SUCCESS;
-	
-	assert(para);
-	
-	AM_TRY(smc_get_openned_dev(dev_no, &dev));
-	
-	if(!dev->drv->set_param)
-	{
-		printf( "driver do not support set_param");
-		ret = AM_SMC_ERR_NOT_SUPPORTED;
-	}
-	
-	if(ret==0)
-	{
-		pthread_mutex_lock(&dev->lock);
-		ret = dev->drv->set_param(dev, para);
-		pthread_mutex_unlock(&dev->lock);
-	}
-	
-	return ret;
+    AM_SMC_Device_t *dev;
+    AM_ErrorCode_t ret = AM_SUCCESS;
+
+    assert(para);
+
+    AM_TRY(smc_get_openned_dev(dev_no, &dev));
+
+    if (!dev->drv->set_param)
+    {
+        printf( "driver do not support set_param");
+        ret = AM_SMC_ERR_NOT_SUPPORTED;
+    }
+
+    if (ret == 0)
+    {
+        pthread_mutex_lock(&dev->lock);
+        ret = dev->drv->set_param(dev, para);
+        pthread_mutex_unlock(&dev->lock);
+    }
+
+    return ret;
 }
 
diff --git a/test/am_smc_test/am_smc.h b/test/am_smc_test/am_smc.h
index 62ad5f3..412dde6 100644
--- a/test/am_smc_test/am_smc.h
+++ b/test/am_smc_test/am_smc.h
@@ -32,18 +32,18 @@
 /**\brief 智能卡模块错误代码*/
 enum AM_SMC_ErrorCode
 {
-	AM_SMC_ERROR_BASE=AM_ERROR_BASE(AM_MOD_SMC),
-	AM_SMC_ERR_INVALID_DEV_NO,           /**< 无效的设备号*/
-	AM_SMC_ERR_BUSY,                     /**< 设备已经打开*/
-	AM_SMC_ERR_NOT_OPENNED,              /**< 设备还没有打开*/
-	AM_SMC_ERR_CANNOT_OPEN_DEV,          /**< 打开设备失败*/
-	AM_SMC_ERR_CANNOT_CREATE_THREAD,     /**< 创建设备失败*/
-	AM_SMC_ERR_TIMEOUT,                  /**< 超时*/
-	AM_SMC_ERR_NOT_SUPPORTED,            /**< 设备不支持此功能*/
-	AM_SMC_ERR_IO,                       /**< 设备输入输出错误*/
-	AM_SMC_ERR_BUF_TOO_SMALL,            /**< 缓冲区太小*/
-	AM_SMC_ERR_NO_CARD,                  /**< 智能卡没有插入*/
-	AM_SMC_ERR_END
+    AM_SMC_ERROR_BASE=AM_ERROR_BASE(AM_MOD_SMC),
+    AM_SMC_ERR_INVALID_DEV_NO,           /**< 无效的设备号*/
+    AM_SMC_ERR_BUSY,                     /**< 设备已经打开*/
+    AM_SMC_ERR_NOT_OPENNED,              /**< 设备还没有打开*/
+    AM_SMC_ERR_CANNOT_OPEN_DEV,          /**< 打开设备失败*/
+    AM_SMC_ERR_CANNOT_CREATE_THREAD,     /**< 创建设备失败*/
+    AM_SMC_ERR_TIMEOUT,                  /**< 超时*/
+    AM_SMC_ERR_NOT_SUPPORTED,            /**< 设备不支持此功能*/
+    AM_SMC_ERR_IO,                       /**< 设备输入输出错误*/
+    AM_SMC_ERR_BUF_TOO_SMALL,            /**< 缓冲区太小*/
+    AM_SMC_ERR_NO_CARD,                  /**< 智能卡没有插入*/
+    AM_SMC_ERR_END
 };
 
 /****************************************************************************
@@ -53,10 +53,10 @@
 /**\brief 智能卡模块事件类型*/
 enum AM_SMC_EventType
 {
-	AM_SMC_EVT_BASE=AM_EVT_TYPE_BASE(AM_MOD_SMC),
-	AM_SMC_EVT_CARD_IN,                  /**< 智能卡插入*/
-	AM_SMC_EVT_CARD_OUT,                 /**< 智能卡拔出*/
-	AM_SMC_EVT_END
+    AM_SMC_EVT_BASE=AM_EVT_TYPE_BASE(AM_MOD_SMC),
+    AM_SMC_EVT_CARD_IN,                  /**< 智能卡插入*/
+    AM_SMC_EVT_CARD_OUT,                 /**< 智能卡拔出*/
+    AM_SMC_EVT_END
 };
 
 
@@ -67,14 +67,14 @@
 /**\brief 智能卡设备开启参数*/
 typedef struct
 {
-	int  enable_thread;                  /**< 创建智能卡状态检测线程*/
+    int  enable_thread;                  /**< 创建智能卡状态检测线程*/
 } AM_SMC_OpenPara_t;
 
 /**\brief 智能卡插入状态*/
 typedef enum
 {
-	AM_SMC_CARD_OUT, /**< 智能卡没有插入*/
-	AM_SMC_CARD_IN   /**< 智能卡已经插入*/
+    AM_SMC_CARD_OUT, /**< 智能卡没有插入*/
+    AM_SMC_CARD_IN   /**< 智能卡已经插入*/
 } AM_SMC_CardStatus_t;
 
 /**\brief 智能卡状态回调*/
@@ -83,24 +83,24 @@
 /** brief 智能卡参数*/
 typedef struct
 {
-	int     f;                 /**<时钟频率转换系数*/
-	int     d;                 /**<波特率系数*/
-	int     n;                 /**<*/
-	int     bwi;               /**<*/
-	int     cwi;               /**<*/
-	int     bgt;               /**<*/
-	int     freq;              /**<时钟频率*/
-	int     recv_invert;       /**<*/
-	int     recv_lsb_msb;      /**<*/
-	int     recv_no_parity;    /**<*/
-	int     xmit_invert;       /**<*/
-	int     xmit_lsb_msb;      /**<*/
-	int     xmit_retries;      /**<*/
-	int     xmit_repeat_dis;   /**<*/
+    int     f;                 /**<时钟频率转换系数*/
+    int     d;                 /**<波特率系数*/
+    int     n;                 /**<*/
+    int     bwi;               /**<*/
+    int     cwi;               /**<*/
+    int     bgt;               /**<*/
+    int     freq;              /**<时钟频率*/
+    int     recv_invert;       /**<*/
+    int     recv_lsb_msb;      /**<*/
+    int     recv_no_parity;    /**<*/
+    int     xmit_invert;       /**<*/
+    int     xmit_lsb_msb;      /**<*/
+    int     xmit_retries;      /**<*/
+    int     xmit_repeat_dis;   /**<*/
 }AM_SMC_Param_t;
 
 /****************************************************************************
- * Function prototypes  
+ * Function prototypes
  ***************************************************************************/
 
 /**\brief 打开智能卡设备
diff --git a/test/am_smc_test/am_smc_internal.h b/test/am_smc_test/am_smc_internal.h
index 049c06a..10bfdd3 100644
--- a/test/am_smc_test/am_smc_internal.h
+++ b/test/am_smc_test/am_smc_internal.h
@@ -33,38 +33,38 @@
 /**\brief 智能卡设备驱动*/
 typedef struct
 {
-	AM_ErrorCode_t (*open) (AM_SMC_Device_t *dev, const AM_SMC_OpenPara_t *para);
-	AM_ErrorCode_t (*close) (AM_SMC_Device_t *dev);
-	AM_ErrorCode_t (*get_status) (AM_SMC_Device_t *dev, AM_SMC_CardStatus_t *status);
-	AM_ErrorCode_t (*reset) (AM_SMC_Device_t *dev, uint8_t *atr, int *len);
-	AM_ErrorCode_t (*read) (AM_SMC_Device_t *dev, uint8_t *data, int *len, int timeout);
-	AM_ErrorCode_t (*write) (AM_SMC_Device_t *dev, const uint8_t *data, int *len, int timeout);
-	AM_ErrorCode_t (*get_param) (AM_SMC_Device_t *dev, AM_SMC_Param_t *para);
-	AM_ErrorCode_t (*set_param) (AM_SMC_Device_t *dev, const AM_SMC_Param_t *para);
-	AM_ErrorCode_t (*active) (AM_SMC_Device_t *dev);
-	AM_ErrorCode_t (*deactive) (AM_SMC_Device_t *dev);
+    AM_ErrorCode_t (*open) (AM_SMC_Device_t *dev, const AM_SMC_OpenPara_t *para);
+    AM_ErrorCode_t (*close) (AM_SMC_Device_t *dev);
+    AM_ErrorCode_t (*get_status) (AM_SMC_Device_t *dev, AM_SMC_CardStatus_t *status);
+    AM_ErrorCode_t (*reset) (AM_SMC_Device_t *dev, uint8_t *atr, int *len);
+    AM_ErrorCode_t (*read) (AM_SMC_Device_t *dev, uint8_t *data, int *len, int timeout);
+    AM_ErrorCode_t (*write) (AM_SMC_Device_t *dev, const uint8_t *data, int *len, int timeout);
+    AM_ErrorCode_t (*get_param) (AM_SMC_Device_t *dev, AM_SMC_Param_t *para);
+    AM_ErrorCode_t (*set_param) (AM_SMC_Device_t *dev, const AM_SMC_Param_t *para);
+    AM_ErrorCode_t (*active) (AM_SMC_Device_t *dev);
+    AM_ErrorCode_t (*deactive) (AM_SMC_Device_t *dev);
 
 } AM_SMC_Driver_t;
 
 /**\brief 智能卡设备*/
 struct AM_SMC_Device
 {
-	int              dev_no;        /**< 输入设备号*/
-	const AM_SMC_Driver_t *drv;     /**< 驱动指针*/
-	void            *drv_data;      /**< 驱动私有数据*/
-	AM_Bool_t        openned;       /**< 设备已经打开*/
-	AM_Bool_t        enable_thread; /**< 状态检测线程是否已经打开*/
-	pthread_t        status_thread; /**< 状态检测线程*/
-	pthread_mutex_t  lock;          /**< 设备数据保护互斥体*/
-	pthread_cond_t   cond;          /**< 设备状态条件变量*/
-	int              flags;         /**< 设备状态*/
-	AM_SMC_StatusCb_t cb;           /**< 状态检测回调函数*/
-	void            *user_data;     /**< 回调函数用户数据*/
+    int              dev_no;        /**< 输入设备号*/
+    const AM_SMC_Driver_t *drv;     /**< 驱动指针*/
+    void            *drv_data;      /**< 驱动私有数据*/
+    AM_Bool_t        openned;       /**< 设备已经打开*/
+    AM_Bool_t        enable_thread; /**< 状态检测线程是否已经打开*/
+    pthread_t        status_thread; /**< 状态检测线程*/
+    pthread_mutex_t  lock;          /**< 设备数据保护互斥体*/
+    pthread_cond_t   cond;          /**< 设备状态条件变量*/
+    int              flags;         /**< 设备状态*/
+    AM_SMC_StatusCb_t cb;           /**< 状态检测回调函数*/
+    void            *user_data;     /**< 回调函数用户数据*/
 };
 
 
 /****************************************************************************
- * Function prototypes  
+ * Function prototypes
  ***************************************************************************/
 
 
diff --git a/test/am_smc_test/am_thread.c b/test/am_smc_test/am_thread.c
index ce01458..c71e619 100644
--- a/test/am_smc_test/am_thread.c
+++ b/test/am_smc_test/am_thread.c
@@ -19,22 +19,22 @@
  ***************************************************************************/
 
 typedef struct {
-	const char       *file;
-	const char       *func;
-	int               line;
+    const char       *file;
+    const char       *func;
+    int               line;
 } AM_ThreadFrame_t;
 
 typedef struct AM_Thread AM_Thread_t;
 struct AM_Thread {
-	AM_Thread_t      *prev;
-	AM_Thread_t      *next;
-	pthread_t         thread;
-	char             *name;
-	void* (*entry)(void*);
-	void             *arg;
-	AM_ThreadFrame_t *frame;
-	int               frame_size;
-	int               frame_top;
+    AM_Thread_t      *prev;
+    AM_Thread_t      *next;
+    pthread_t         thread;
+    char             *name;
+    void* (*entry)(void*);
+    void             *arg;
+    AM_ThreadFrame_t *frame;
+    int               frame_size;
+    int               frame_top;
 };
 
 /****************************************************************************
@@ -50,78 +50,78 @@
 
 static void thread_init(void)
 {
-	AM_Thread_t *th;
-	
-	th = malloc(sizeof(AM_Thread_t));
-	if(!th)
-	{
-		printf("not enough memory");
-		return;
-	}
-	
-	th->thread= pthread_self();
-	th->name  = strdup("main");
-	th->entry = NULL;
-	th->arg   = NULL;
-	th->prev  = NULL;
-	th->next  = NULL;
-	th->frame = NULL;
-	th->frame_size = 0;
-	th->frame_top  = 0;
-	
-	threads = th;
-	
-	printf("Register thread \"main\"");
+    AM_Thread_t *th;
+
+    th = malloc(sizeof(AM_Thread_t));
+    if (!th)
+    {
+        printf("not enough memory");
+        return;
+    }
+
+    th->thread = pthread_self();
+    th->name  = strdup("main");
+    th->entry = NULL;
+    th->arg   = NULL;
+    th->prev  = NULL;
+    th->next  = NULL;
+    th->frame = NULL;
+    th->frame_size = 0;
+    th->frame_top  = 0;
+
+    threads = th;
+
+    printf("Register thread \"main\"");
 }
 
 static void thread_remove(AM_Thread_t *th)
 {
-	if(th->prev)
-		th->prev->next = th->next;
-	else
-		threads = th->next;
-	if(th->next)
-		th->next->prev = th->prev;
-	
-	if(th->name)
-		free(th->name);
-	if(th->frame)
-		free(th->frame);
-	
-	free(th);
+    if (th->prev)
+        th->prev->next = th->next;
+    else
+        threads = th->next;
+    if (th->next)
+        th->next->prev = th->prev;
+
+    if (th->name)
+        free(th->name);
+    if (th->frame)
+        free(th->frame);
+
+    free(th);
 }
 
 static void* thread_entry(void *arg)
 {
-	AM_Thread_t *th = (AM_Thread_t*)arg;
-	void *r;
-	
-	pthread_mutex_lock(&lock);
-	th->thread = pthread_self();
-	pthread_mutex_unlock(&lock);
-	
-	printf("Register thread \"%s\" %p", th->name, (void*)th->thread);
-	
-	r = th->entry(th->arg);
-	
-	pthread_mutex_lock(&lock);
-	thread_remove(th);
-	pthread_mutex_unlock(&lock);
-	
-	return r;
+    AM_Thread_t *th = (AM_Thread_t*)arg;
+    void *r;
+
+    pthread_mutex_lock(&lock);
+    th->thread = pthread_self();
+    pthread_mutex_unlock(&lock);
+
+    printf("Register thread \"%s\" %p", th->name, (void*)th->thread);
+
+    r = th->entry(th->arg);
+
+    pthread_mutex_lock(&lock);
+    thread_remove(th);
+    pthread_mutex_unlock(&lock);
+
+    return r;
 }
 
 static AM_Thread_t* thread_get(pthread_t t)
 {
-	AM_Thread_t *th;
-	
-	for(th=threads; th; th=th->next)
-	{
-		if(th->thread==t)
-			return th;
-	}
-	
-	return NULL;
+    AM_Thread_t *th;
+
+    for (th = threads; th; th = th->next)
+    {
+        if (th->thread == t)
+            return th;
+    }
+
+    return NULL;
 }
 
 /****************************************************************************
@@ -137,51 +137,51 @@
  * \return 成功返回0,失败返回错误代码
  */
 int AM_pthread_create_name(pthread_t *thread,
-		const pthread_attr_t *attr,
-		void* (*start_routine)(void*),
-		void *arg,
-		const char *name)
+        const pthread_attr_t *attr,
+        void* (*start_routine)(void*),
+        void *arg,
+        const char *name)
 {
-	AM_Thread_t *th;
-	int ret;
-	
-	pthread_once(&once, thread_init);
-	
-	th = malloc(sizeof(AM_Thread_t));
-	if(!th)
-	{
-		printf("not enough memory");
-		return -1;
-	}
-	
-	th->thread= -1;
-	th->name  = name?strdup(name):NULL;
-	th->entry = start_routine;
-	th->arg   = arg;
-	th->prev  = NULL;
-	th->frame = NULL;
-	th->frame_size = 0;
-	th->frame_top  = 0;
-	
-	pthread_mutex_lock(&lock);
-	if(threads)
-		threads->prev = th;
-	th->next = threads;
-	threads = th;
-	pthread_mutex_unlock(&lock);
-	
-	ret = pthread_create(thread, attr, thread_entry, th);
-	if(ret)
-	{
-		printf("create thread failed");
-		pthread_mutex_lock(&lock);
-		thread_remove(th);
-		pthread_mutex_unlock(&lock);
-		
-		return ret;
-	}
-	
-	return 0;
+    AM_Thread_t *th;
+    int ret;
+
+    pthread_once(&once, thread_init);
+
+    th = malloc(sizeof(AM_Thread_t));
+    if (!th)
+    {
+        printf("not enough memory");
+        return -1;
+    }
+
+    th->thread = -1;
+    th->name  = name ? strdup(name) : NULL;
+    th->entry = start_routine;
+    th->arg   = arg;
+    th->prev  = NULL;
+    th->frame = NULL;
+    th->frame_size = 0;
+    th->frame_top  = 0;
+
+    pthread_mutex_lock(&lock);
+    if (threads)
+        threads->prev = th;
+    th->next = threads;
+    threads = th;
+    pthread_mutex_unlock(&lock);
+
+    ret = pthread_create(thread, attr, thread_entry, th);
+    if (ret)
+    {
+        printf("create thread failed");
+        pthread_mutex_lock(&lock);
+        thread_remove(th);
+        pthread_mutex_unlock(&lock);
+
+        return ret;
+    }
+
+    return 0;
 }
 
 /**\brief 结束当前线程
@@ -189,21 +189,21 @@
  */
 void AM_pthread_exit(void *r)
 {
-	AM_Thread_t *th;
-	
-	pthread_once(&once, thread_init);
-	
-	pthread_mutex_lock(&lock);
-	
-	th = thread_get(pthread_self());
-	if(th)
-		thread_remove(th);
-	else
-		printf("thread %p is not registered", (void*)pthread_self());
-		
-	pthread_mutex_unlock(&lock);
-	
-	pthread_exit(r);
+    AM_Thread_t *th;
+
+    pthread_once(&once, thread_init);
+
+    pthread_mutex_lock(&lock);
+
+    th = thread_get(pthread_self());
+    if (th)
+        thread_remove(th);
+    else
+        printf("thread %p is not registered", (void*)pthread_self());
+
+    pthread_mutex_unlock(&lock);
+
+    pthread_exit(r);
 }
 
 /**\brief 记录当前线程进入一个函数
@@ -214,45 +214,45 @@
  */
 int AM_pthread_enter(const char *file, const char *func, int line)
 {
-	AM_Thread_t *th;
-	int ret = 0;
-	
-	pthread_once(&once, thread_init);
-	
-	pthread_mutex_lock(&lock);
-	
-	th = thread_get(pthread_self());
-	if(th)
-	{
-		if((th->frame_top+1)>=th->frame_size)
-		{
-			AM_ThreadFrame_t *f;
-			int size = AM_MAX(th->frame_size*2, 16);
-			
-			f = realloc(th->frame, sizeof(AM_ThreadFrame_t)*size);
-			if(!f)
-			{
-				printf("not enough memory");
-				ret = -1;
-				goto error;
-			}
-			
-			th->frame = f;
-			th->frame_size = size;
-		}
-		th->frame[th->frame_top].file = file;
-		th->frame[th->frame_top].func = func;
-		th->frame[th->frame_top].line = line;
-		th->frame_top++;
-	}
-	else
-	{
-		printf("thread %p is not registered", (void*)pthread_self());
-		ret = -1;
-	}
+    AM_Thread_t *th;
+    int ret = 0;
+
+    pthread_once(&once, thread_init);
+
+    pthread_mutex_lock(&lock);
+
+    th = thread_get(pthread_self());
+    if (th)
+    {
+        if ((th->frame_top + 1) >= th->frame_size)
+        {
+            AM_ThreadFrame_t *f;
+            int size = AM_MAX(th->frame_size * 2, 16);
+
+            f = realloc(th->frame, sizeof(AM_ThreadFrame_t) * size);
+            if (!f)
+            {
+                printf("not enough memory");
+                ret = -1;
+                goto error;
+            }
+
+            th->frame = f;
+            th->frame_size = size;
+        }
+        th->frame[th->frame_top].file = file;
+        th->frame[th->frame_top].func = func;
+        th->frame[th->frame_top].line = line;
+        th->frame_top++;
+    }
+    else
+    {
+        printf("thread %p is not registered", (void*)pthread_self());
+        ret = -1;
+    }
 error:
-	pthread_mutex_unlock(&lock);
-	return ret;
+    pthread_mutex_unlock(&lock);
+    return ret;
 }
 
 /**\brief 记录当前线程离开一个函数
@@ -263,28 +263,28 @@
  */
 int AM_pthread_leave(const char *file, const char *func, int line)
 {
-	AM_Thread_t *th;
-	
-	pthread_once(&once, thread_init);
-	
-	pthread_mutex_lock(&lock);
-	
-	th = thread_get(pthread_self());
-	if(th)
-	{
-		if(!th->frame_top)
-			printf("AM_pthread_enter and AM_pthread_leave mismatch");
-		else
-			th->frame_top--;
-	}
-	else
-	{
-		printf("thread %p is not registered", (void*)pthread_self());
-	}
-		
-	pthread_mutex_unlock(&lock);
-	
-	return 0;
+    AM_Thread_t *th;
+
+    pthread_once(&once, thread_init);
+
+    pthread_mutex_lock(&lock);
+
+    th = thread_get(pthread_self());
+    if (th)
+    {
+        if (!th->frame_top)
+            printf("AM_pthread_enter and AM_pthread_leave mismatch");
+        else
+            th->frame_top--;
+    }
+    else
+    {
+        printf("thread %p is not registered", (void*)pthread_self());
+    }
+
+    pthread_mutex_unlock(&lock);
+
+    return 0;
 }
 
 /**\brief 打印当前所有注册线程的状态信息
@@ -292,28 +292,28 @@
  */
 int AM_pthread_dump(void)
 {
-	AM_Thread_t *th;
-	int i, l, n;
-	
-	pthread_once(&once, thread_init);
-	
-	pthread_mutex_lock(&lock);
-	
-	for(th=threads,i=0; th; th=th->next, i++)
-	{
-		if(th->thread==-1)
-			continue;
-		
-		fprintf(stdout, "Thread %d (%p:%s)\n", i, (void*)th->thread, th->name?th->name:"");
-		for(l=th->frame_top-1,n=0; l>=0; l--,n++)
-		{
-			AM_ThreadFrame_t *f = &th->frame[l];
-			fprintf(stdout, "\t<%d> %s line %d [%s]\n", n, f->func?f->func:NULL, f->line, f->file?f->file:NULL);
-		}
-	}
-	
-	pthread_mutex_unlock(&lock);
-	
-	return 0;
+    AM_Thread_t *th;
+    int i, l, n;
+
+    pthread_once(&once, thread_init);
+
+    pthread_mutex_lock(&lock);
+
+    for (th = threads, i = 0; th; th = th->next, i++)
+    {
+        if (th->thread == -1)
+            continue;
+
+        fprintf(stdout, "Thread %d (%p:%s)\n", i, (void*)th->thread, th->name?th->name:"");
+        for (l = th->frame_top - 1, n = 0; l >= 0; l--, n++)
+        {
+            AM_ThreadFrame_t *f = &th->frame[l];
+            fprintf(stdout, "\t<%d> %s line %d [%s]\n", n, f->func ? f->func : NULL, f->line, f->file ? f->file : NULL);
+        }
+    }
+
+    pthread_mutex_unlock(&lock);
+
+    return 0;
 }
 
diff --git a/test/am_smc_test/am_thread.h b/test/am_smc_test/am_thread.h
index 27992e6..e6d6cb5 100644
--- a/test/am_smc_test/am_thread.h
+++ b/test/am_smc_test/am_thread.h
@@ -44,9 +44,9 @@
 
 /**\brief AM_THREAD_ENTER()和AM_THREAD_LEAVE()对中间包括函数中的各个语句*/
 #define AM_THREAD_FUNC(do)\
-	AM_THREAD_ENTER();\
-	{do;}\
-	AM_THREAD_LEAVE();
+    AM_THREAD_ENTER();\
+    {do;}\
+    AM_THREAD_LEAVE();
 
 #else /*AM_THREAD_ENABLE*/
 
@@ -58,7 +58,7 @@
 #endif /*AM_THREAD_ENABLE*/
 
 /****************************************************************************
- * Function prototypes  
+ * Function prototypes
  ***************************************************************************/
 
 #ifdef AM_THREAD_ENABLE
@@ -72,10 +72,10 @@
  * \return 成功返回0,失败返回错误代码
  */
 int AM_pthread_create_name(pthread_t *thread,
-		const pthread_attr_t *attr,
-		void* (*start_routine)(void*),
-		void *arg,
-		const char *name);
+        const pthread_attr_t *attr,
+        void* (*start_routine)(void*),
+        void *arg,
+        const char *name);
 
 /**\brief 结束当前线程
  * \param[in] r 返回值
diff --git a/test/am_smc_test/am_time.c b/test/am_smc_test/am_time.c
index ac4063d..bd32a84 100644
--- a/test/am_smc_test/am_time.c
+++ b/test/am_smc_test/am_time.c
@@ -22,7 +22,7 @@
  ***************************************************************************/
 #ifdef ANDROID
 #undef CLOCK_REALTIME
-#define CLOCK_REALTIME	CLOCK_MONOTONIC
+#define CLOCK_REALTIME    CLOCK_MONOTONIC
 #endif
 
 /****************************************************************************
@@ -37,16 +37,16 @@
  */
 AM_ErrorCode_t AM_TIME_GetClock(int *clock)
 {
-	struct timespec ts;
-	int ms;
-	
-	assert(clock);
-	
-	clock_gettime(CLOCK_REALTIME, &ts);
-	ms = ts.tv_sec*1000+ts.tv_nsec/1000000;
-	*clock = ms;
-	
-	return AM_SUCCESS;
+    struct timespec ts;
+    int ms;
+
+    assert(clock);
+
+    clock_gettime(CLOCK_REALTIME, &ts);
+    ms = ts.tv_sec*1000+ts.tv_nsec/1000000;
+    *clock = ms;
+
+    return AM_SUCCESS;
 }
 
 /**\brief 得到开机到当前系统运行的时间,格式为struct timespec
@@ -57,11 +57,11 @@
  */
 AM_ErrorCode_t AM_TIME_GetTimeSpec(struct timespec *ts)
 {
-	assert(ts);
-	
-	clock_gettime(CLOCK_REALTIME, ts);
-	
-	return AM_SUCCESS;
+    assert(ts);
+
+    clock_gettime(CLOCK_REALTIME, ts);
+
+    return AM_SUCCESS;
 }
 
 /**\brief 得到若干毫秒后的timespec值
@@ -74,30 +74,30 @@
  */
 AM_ErrorCode_t AM_TIME_GetTimeSpecTimeout(int timeout, struct timespec *ts)
 {
-	struct timespec ots;
-	int left, diff;
-	
-	assert(ts);
-	
-	clock_gettime(CLOCK_REALTIME, &ots);
-	
-	ts->tv_sec  = ots.tv_sec + timeout/1000;
-	ts->tv_nsec = ots.tv_nsec;
-	
-	left = timeout % 1000;
-	left *= 1000000;
-	diff = 1000000000-ots.tv_nsec;
+    struct timespec ots;
+    int left, diff;
 
-	if(diff<=left)
-	{
-		ts->tv_sec++;
-		ts->tv_nsec = left-diff;
-	}
-	else
-	{
-		ts->tv_nsec += left;
-	}
+    assert(ts);
 
-	return AM_SUCCESS;
+    clock_gettime(CLOCK_REALTIME, &ots);
+
+    ts->tv_sec  = ots.tv_sec + timeout/1000;
+    ts->tv_nsec = ots.tv_nsec;
+
+    left = timeout % 1000;
+    left *= 1000000;
+    diff = 1000000000-ots.tv_nsec;
+
+    if (diff <= left)
+    {
+        ts->tv_sec++;
+        ts->tv_nsec = left-diff;
+    }
+    else
+    {
+        ts->tv_nsec += left;
+    }
+
+    return AM_SUCCESS;
 }
 
diff --git a/test/am_smc_test/am_time.h b/test/am_smc_test/am_time.h
index c85e2b0..a036710 100644
--- a/test/am_smc_test/am_time.h
+++ b/test/am_smc_test/am_time.h
@@ -23,9 +23,9 @@
  * Macro definitions
  ***************************************************************************/
 #ifdef ANDROID
-extern int  __pthread_cond_timedwait(pthread_cond_t*, 
+extern int  __pthread_cond_timedwait(pthread_cond_t*,
                                      pthread_mutex_t*,
-                                     const struct timespec*, 
+                                     const struct timespec*,
                                      clockid_t);
 #define pthread_cond_timedwait(c, m, a) __pthread_cond_timedwait(c, m, a, CLOCK_MONOTONIC);
 #endif
@@ -36,7 +36,7 @@
 
 
 /****************************************************************************
- * Function prototypes  
+ * Function prototypes
  ***************************************************************************/
 
 /**\brief 得到开机到当前系统运行的时间,单位为毫秒
diff --git a/test/am_smc_test/am_types.h b/test/am_smc_test/am_types.h
index f6c44e6..3b14de5 100644
--- a/test/am_smc_test/am_types.h
+++ b/test/am_smc_test/am_types.h
@@ -41,44 +41,44 @@
 /**\brief The module's index */
 enum AM_MOD_ID
 {
-	AM_MOD_EVT,    /**< Event module*/
-	AM_MOD_DMX,    /**< Demux module*/
-	AM_MOD_DVR,    /**< DVR module*/
-	AM_MOD_NET,    /**< Network manager module*/
-	AM_MOD_OSD,    /**< OSD module*/
-	AM_MOD_AV,     /**< AV decoder module*/
-	AM_MOD_AOUT,   /**< Audio output device module*/
-	AM_MOD_VOUT,   /**< Video output device module*/
-	AM_MOD_SMC,    /**< Smartcard module*/
-	AM_MOD_INP,    /**< Input device module*/
-	AM_MOD_FEND,   /**< DVB frontend device module*/
-	AM_MOD_DSC,    /**< Descrambler device module*/
-	AM_MOD_CFG,    /**< Configure file manager module*/
-	AM_MOD_SI,     /**< SI decoder module*/
-	AM_MOD_SCAN,   /**< Channel scanner module*/
-	AM_MOD_EPG,    /**< EPG scanner module*/
-	AM_MOD_IMG,    /**< Image loader module*/
-	AM_MOD_FONT,   /**< Font manager module*/
-	AM_MOD_DB,     /**< Database module*/
-	AM_MOD_GUI,    /**< GUI module*/
-	AM_MOD_REC,    /**< Recorder module*/
-	AM_MOD_TV,     /**< TV manager module*/
-	AM_MOD_SUB,    /**< Subtitle module*/
-	AM_MOD_SUB2,   /**< Subtitle(version 2) module*/
-	AM_MOD_TT,     /**< Teletext module*/
-	AM_MOD_TT2,    /**< Teletext(version 2) module*/
-	AM_MOD_FEND_DISEQCCMD,/**< Diseqc command module*/
-	AM_MOD_FENDCTRL, /**< DVB frontend high level control module*/
-	AM_MOD_PES,    /**< PES parser module*/
-	AM_MOD_CAMAN,  /**< CA manager module*/
-	AM_MOD_CI,     /**< DVB-CI module*/
-	AM_MOD_USERDATA, /**< MPEG user data reader device module*/
-	AM_MOD_CC,     /**< Close caption module*/
-	AM_MOD_AD,     /**< Audio description module*/
-	AM_MOD_UPD,    /**< Uploader module*/
-	AM_MOD_TFILE, /*File wrapper module*/
-	AM_MOD_SCTE27,
-	AM_MOD_MAX
+    AM_MOD_EVT,    /**< Event module*/
+    AM_MOD_DMX,    /**< Demux module*/
+    AM_MOD_DVR,    /**< DVR module*/
+    AM_MOD_NET,    /**< Network manager module*/
+    AM_MOD_OSD,    /**< OSD module*/
+    AM_MOD_AV,     /**< AV decoder module*/
+    AM_MOD_AOUT,   /**< Audio output device module*/
+    AM_MOD_VOUT,   /**< Video output device module*/
+    AM_MOD_SMC,    /**< Smartcard module*/
+    AM_MOD_INP,    /**< Input device module*/
+    AM_MOD_FEND,   /**< DVB frontend device module*/
+    AM_MOD_DSC,    /**< Descrambler device module*/
+    AM_MOD_CFG,    /**< Configure file manager module*/
+    AM_MOD_SI,     /**< SI decoder module*/
+    AM_MOD_SCAN,   /**< Channel scanner module*/
+    AM_MOD_EPG,    /**< EPG scanner module*/
+    AM_MOD_IMG,    /**< Image loader module*/
+    AM_MOD_FONT,   /**< Font manager module*/
+    AM_MOD_DB,     /**< Database module*/
+    AM_MOD_GUI,    /**< GUI module*/
+    AM_MOD_REC,    /**< Recorder module*/
+    AM_MOD_TV,     /**< TV manager module*/
+    AM_MOD_SUB,    /**< Subtitle module*/
+    AM_MOD_SUB2,   /**< Subtitle(version 2) module*/
+    AM_MOD_TT,     /**< Teletext module*/
+    AM_MOD_TT2,    /**< Teletext(version 2) module*/
+    AM_MOD_FEND_DISEQCCMD,/**< Diseqc command module*/
+    AM_MOD_FENDCTRL, /**< DVB frontend high level control module*/
+    AM_MOD_PES,    /**< PES parser module*/
+    AM_MOD_CAMAN,  /**< CA manager module*/
+    AM_MOD_CI,     /**< DVB-CI module*/
+    AM_MOD_USERDATA, /**< MPEG user data reader device module*/
+    AM_MOD_CC,     /**< Close caption module*/
+    AM_MOD_AD,     /**< Audio description module*/
+    AM_MOD_UPD,    /**< Uploader module*/
+    AM_MOD_TFILE, /*File wrapper module*/
+    AM_MOD_SCTE27,
+    AM_MOD_MAX
 };
 
 /**\brief Get the error code base of each module
diff --git a/test/am_smc_test/am_util.h b/test/am_smc_test/am_util.h
index 9209dd7..d89351f 100644
--- a/test/am_smc_test/am_util.h
+++ b/test/am_smc_test/am_util.h
@@ -62,54 +62,54 @@
 
 /**\brief 检查如果返回值是否错误,返回错误代码给调用函数*/
 #define AM_TRY(_func) \
-	AM_MACRO_BEGIN\
-	AM_ErrorCode_t _ret;\
-	if ((_ret=(_func))!=AM_SUCCESS)\
-		return _ret;\
-	AM_MACRO_END
+    AM_MACRO_BEGIN\
+    AM_ErrorCode_t _ret;\
+    if ((_ret=(_func))!=AM_SUCCESS)\
+        return _ret;\
+    AM_MACRO_END
 
 /**\brief 检查返回值是否错误,如果错误,跳转到final标号。注意:函数中必须定义"AM_ErrorCode_t ret"和标号"final"*/
 #define AM_TRY_FINAL(_func)\
-	AM_MACRO_BEGIN\
-	if ((ret=(_func))!=AM_SUCCESS)\
-		goto final;\
-	AM_MACRO_END
+    AM_MACRO_BEGIN\
+    if ((ret=(_func))!=AM_SUCCESS)\
+        goto final;\
+    AM_MACRO_END
 
 /**\brief 开始解析一个被指定字符隔开的字符串*/
 #define AM_TOKEN_PARSE_BEGIN(_str, _delim, _token) \
-	{\
-	char *_strb =  strdup(_str);\
-	if (_strb) {\
-		_token = strtok(_strb, _delim);\
-		while (_token != NULL) {
-	
+    {\
+    char *_strb =  strdup(_str);\
+    if (_strb) {\
+        _token = strtok(_strb, _delim);\
+        while (_token != NULL) {
+
 #define AM_TOKEN_PARSE_END(_str, _delim, _token) \
-		_token = strtok(NULL, _delim);\
-		}\
-		free(_strb);\
-	}\
-	}
-	
+        _token = strtok(NULL, _delim);\
+        }\
+        free(_strb);\
+    }\
+    }
+
 
 /**\brief 从一个被指定字符隔开的字符串中取指定位置的值,int类型,如未找到指定位置,则使用默认值_default代替*/
 #define AM_TOKEN_VALUE_INT(_str, _delim, _index, _default) \
-	({\
-		char *token;\
-		char *_strbak = strdup(_str);\
-		int counter = 0;\
-		int val = _default;\
-		if (_strbak != NULL) {\
-			AM_TOKEN_PARSE_BEGIN(_strbak, _delim, token)\
-				if (counter == (_index)) {\
-					val = atoi(token);\
-					break;\
-				}\
-				counter++;\
-			AM_TOKEN_PARSE_END(_strbak, _delim, token)\
-			free(_strbak);\
-		}\
-		val;\
-	})
+    ({\
+        char *token;\
+        char *_strbak = strdup(_str);\
+        int counter = 0;\
+        int val = _default;\
+        if (_strbak != NULL) {\
+            AM_TOKEN_PARSE_BEGIN(_strbak, _delim, token)\
+                if (counter == (_index)) {\
+                    val = atoi(token);\
+                    break;\
+                }\
+                counter++;\
+            AM_TOKEN_PARSE_END(_strbak, _delim, token)\
+            free(_strbak);\
+        }\
+        val;\
+    })
 
 /****************************************************************************
  * Type definitions
@@ -117,7 +117,7 @@
 
 
 /****************************************************************************
- * Function prototypes  
+ * Function prototypes
  ***************************************************************************/
 
 
diff --git a/test/am_smc_test/aml.c b/test/am_smc_test/aml.c
index 403ea55..79e1797 100644
--- a/test/am_smc_test/aml.c
+++ b/test/am_smc_test/aml.c
@@ -65,163 +65,163 @@
 
 AM_ErrorCode_t aml_open (AM_SMC_Device_t *dev, const AM_SMC_OpenPara_t *para)
 {
-	char name[PATH_MAX];
-	int fd;
-	
-	snprintf(name, sizeof(name), "/dev/smc%d", dev->dev_no);
-	fd = open(name, O_RDWR);
-	if(fd==-1)
-	{
-		printf("cannot open device \"%s\"", name);
-		return AM_SMC_ERR_CANNOT_OPEN_DEV;
-	}
-	
-	dev->drv_data = (void*)fd;
-	return AM_SUCCESS;
+    char name[PATH_MAX];
+    int fd;
+
+    snprintf(name, sizeof(name), "/dev/smc%d", dev->dev_no);
+    fd = open(name, O_RDWR);
+    if (fd == -1)
+    {
+        printf("cannot open device \"%s\"", name);
+        return AM_SMC_ERR_CANNOT_OPEN_DEV;
+    }
+
+    dev->drv_data = (void*)fd;
+    return AM_SUCCESS;
 }
 
 AM_ErrorCode_t aml_close (AM_SMC_Device_t *dev)
 {
-	int fd = (int)dev->drv_data;
-	
-	close(fd);
-	return AM_SUCCESS;
+    int fd = (int)dev->drv_data;
+
+    close(fd);
+    return AM_SUCCESS;
 }
 
 AM_ErrorCode_t aml_get_status (AM_SMC_Device_t *dev, AM_SMC_CardStatus_t *status)
 {
-	int fd = (int)dev->drv_data;
-	int ds;
-	
-	if(ioctl(fd, AMSMC_IOC_GET_STATUS, &ds))
-	{
-		printf("get card status failed \"%s\"", strerror(errno));
-		return AM_SMC_ERR_IO;
-	}
-	
-	*status = ds ? AM_SMC_CARD_IN : AM_SMC_CARD_OUT;
-	
-	return AM_SUCCESS;
+    int fd = (int)dev->drv_data;
+    int ds;
+
+    if (ioctl(fd, AMSMC_IOC_GET_STATUS, &ds))
+    {
+        printf("get card status failed \"%s\"", strerror(errno));
+        return AM_SMC_ERR_IO;
+    }
+
+    *status = ds ? AM_SMC_CARD_IN : AM_SMC_CARD_OUT;
+
+    return AM_SUCCESS;
 }
 
 AM_ErrorCode_t aml_reset (AM_SMC_Device_t *dev, uint8_t *atr, int *len)
 {
-	int fd = (int)dev->drv_data;
-	struct am_smc_atr abuf;
-	
-	if(ioctl(fd, AMSMC_IOC_RESET, &abuf))
-	{
-		printf("reset the card failed \"%s\"", strerror(errno));
-		return AM_SMC_ERR_IO;
-	}
-	
-	memcpy(atr, abuf.atr, abuf.atr_len);
-	*len = abuf.atr_len;
-	
-	return AM_SUCCESS;
+    int fd = (int)dev->drv_data;
+    struct am_smc_atr abuf;
+
+    if (ioctl(fd, AMSMC_IOC_RESET, &abuf))
+    {
+        printf("reset the card failed \"%s\"", strerror(errno));
+        return AM_SMC_ERR_IO;
+    }
+
+    memcpy(atr, abuf.atr, abuf.atr_len);
+    *len = abuf.atr_len;
+
+    return AM_SUCCESS;
 }
 
 AM_ErrorCode_t aml_read (AM_SMC_Device_t *dev, uint8_t *data, int *len, int timeout)
 {
-	struct pollfd pfd;
-	int fd = (int)dev->drv_data;
-	int ret;
-	
-	pfd.fd = fd;
-	pfd.events = POLLIN;
-	
-	ret = poll(&pfd, 1, timeout);
-	if(ret!=1)
-	{
-		return AM_SMC_ERR_TIMEOUT;
-	}
-	
-	ret = read(fd, data, *len);
-	if(ret<0)
-	{
-		printf("card read error %s", strerror(errno));
-		return AM_SMC_ERR_IO;
-	}
-	
-	*len = ret;
-	return AM_SUCCESS;
+    struct pollfd pfd;
+    int fd = (int)dev->drv_data;
+    int ret;
+
+    pfd.fd = fd;
+    pfd.events = POLLIN;
+
+    ret = poll(&pfd, 1, timeout);
+    if (ret != 1)
+    {
+        return AM_SMC_ERR_TIMEOUT;
+    }
+
+    ret = read(fd, data, *len);
+    if (ret < 0)
+    {
+        printf("card read error %s", strerror(errno));
+        return AM_SMC_ERR_IO;
+    }
+
+    *len = ret;
+    return AM_SUCCESS;
 }
 
 AM_ErrorCode_t aml_write (AM_SMC_Device_t *dev, const uint8_t *data, int *len, int timeout)
 {
-	struct pollfd pfd;
-	int fd = (int)dev->drv_data;
-	int ret;
-	
-	pfd.fd = fd;
-	pfd.events = POLLOUT;
-	
-	ret = poll(&pfd, 1, timeout);
-	if(ret!=1)
-	{
-		return AM_SMC_ERR_TIMEOUT;
-	}
-	
-	ret = write(fd, data, *len);
-	if(ret<0)
-	{
-		printf("card write error %s", strerror(errno));
-		return AM_SMC_ERR_IO;
-	}
-	
-	*len = ret;
-	return AM_SUCCESS;
+    struct pollfd pfd;
+    int fd = (int)dev->drv_data;
+    int ret;
+
+    pfd.fd = fd;
+    pfd.events = POLLOUT;
+
+    ret = poll(&pfd, 1, timeout);
+    if (ret != 1)
+    {
+        return AM_SMC_ERR_TIMEOUT;
+    }
+
+    ret = write(fd, data, *len);
+    if (ret < 0)
+    {
+        printf("card write error %s", strerror(errno));
+        return AM_SMC_ERR_IO;
+    }
+
+    *len = ret;
+    return AM_SUCCESS;
 }
 
 AM_ErrorCode_t aml_get_param (AM_SMC_Device_t *dev, AM_SMC_Param_t *para)
 {
-	int fd = (int)dev->drv_data;
-	
-	if(ioctl(fd, AMSMC_IOC_GET_PARAM, para))
-	{
-		printf("get card params failed \"%s\"", strerror(errno));
-		return AM_SMC_ERR_IO;
-	}
-	
-	return AM_SUCCESS;
+    int fd = (int)dev->drv_data;
+
+    if (ioctl(fd, AMSMC_IOC_GET_PARAM, para))
+    {
+        printf("get card params failed \"%s\"", strerror(errno));
+        return AM_SMC_ERR_IO;
+    }
+
+    return AM_SUCCESS;
 }
 
 AM_ErrorCode_t aml_set_param (AM_SMC_Device_t *dev, const AM_SMC_Param_t *para)
 {
-	int fd = (int)dev->drv_data;
-	
-	if(ioctl(fd, AMSMC_IOC_SET_PARAM, para))
-	{
-		printf("set card params failed \"%s\"", strerror(errno));
-		return AM_SMC_ERR_IO;
-	}
-	
-	return AM_SUCCESS;
+    int fd = (int)dev->drv_data;
+
+    if (ioctl(fd, AMSMC_IOC_SET_PARAM, para))
+    {
+        printf("set card params failed \"%s\"", strerror(errno));
+        return AM_SMC_ERR_IO;
+    }
+
+    return AM_SUCCESS;
 }
 
 AM_ErrorCode_t aml_active (AM_SMC_Device_t *dev)
 {
-	int fd = (int)dev->drv_data;
-	
-	if(ioctl(fd, AMSMC_IOC_ACTIVE, 0))
-	{
-		printf("active card failed \"%s\"", strerror(errno));
-		return AM_SMC_ERR_IO;
-	}
-	
-	return AM_SUCCESS;
+    int fd = (int)dev->drv_data;
+
+    if (ioctl(fd, AMSMC_IOC_ACTIVE, 0))
+    {
+        printf("active card failed \"%s\"", strerror(errno));
+        return AM_SMC_ERR_IO;
+    }
+
+    return AM_SUCCESS;
 }
 
 AM_ErrorCode_t aml_deactive (AM_SMC_Device_t *dev)
 {
-	int fd = (int)dev->drv_data;
-	
-	if(ioctl(fd, AMSMC_IOC_DEACTIVE, 0))
-	{
-		printf("deactive card failed \"%s\"", strerror(errno));
-		return AM_SMC_ERR_IO;
-	}
-	
-	return AM_SUCCESS;
+    int fd = (int)dev->drv_data;
+
+    if (ioctl(fd, AMSMC_IOC_DEACTIVE, 0))
+    {
+        printf("deactive card failed \"%s\"", strerror(errno));
+        return AM_SMC_ERR_IO;
+    }
+
+    return AM_SUCCESS;
 }
 
diff --git a/test/am_smc_test/amsmc.h b/test/am_smc_test/amsmc.h
index fd8452c..15dd5ec 100644
--- a/test/am_smc_test/amsmc.h
+++ b/test/am_smc_test/amsmc.h
@@ -24,30 +24,30 @@
 #define AMSMC_MAX_ATR_LEN    33
 
 enum {
-	AMSMC_CARDOUT = 0,
-	AMSMC_CARDIN = 1
+    AMSMC_CARDOUT = 0,
+    AMSMC_CARDIN = 1
 };
 
 struct am_smc_atr {
-	char    atr[AMSMC_MAX_ATR_LEN];
-	int     atr_len;
+    char    atr[AMSMC_MAX_ATR_LEN];
+    int     atr_len;
 };
 
 struct am_smc_param {
-	int     f;
-	int     d;
-	int     n;
-	int     bwi;
-	int     cwi;
-	int     bgt;
-	int     freq;
-	int     recv_invert;
-	int     recv_lsb_msb;
-	int     recv_no_parity;
-	int     xmit_invert;
-	int     xmit_lsb_msb;
-	int     xmit_retries;
-	int     xmit_repeat_dis;
+    int     f;
+    int     d;
+    int     n;
+    int     bwi;
+    int     cwi;
+    int     bgt;
+    int     freq;
+    int     recv_invert;
+    int     recv_lsb_msb;
+    int     recv_no_parity;
+    int     xmit_invert;
+    int     xmit_lsb_msb;
+    int     xmit_retries;
+    int     xmit_repeat_dis;
 };
 
 #define AMSMC_IOC_MAGIC  'C'
diff --git a/test/dvr_play_test/dvr_play_test.c b/test/dvr_play_test/dvr_play_test.c
index 5f4724b..4af7071 100644
--- a/test/dvr_play_test/dvr_play_test.c
+++ b/test/dvr_play_test/dvr_play_test.c
@@ -31,7 +31,7 @@
     fprintf(stderr, "*resume\n");
     fprintf(stderr, "*ff speed(1=1X,2=4X,3=6X)\n");
     fprintf(stderr, "*fb speed(1=1X,2=4X,3=6X)\n");
-    fprintf(stderr, "*seek time_in_msecond\n");
+    fprintf(stderr, "*seek time_in_ms\n");
     fprintf(stderr, "*quit\n");
     fprintf(stderr, "==================\n");
 }
@@ -85,7 +85,7 @@
                 sscanf(buf + 4, "%d", &time);
                 dvr_playback_seek(handle, 0,time);
             } else {
-                fprintf(stderr, "Unkown command: %s\n", buf);
+                fprintf(stderr, "Unknown command: %s\n", buf);
                 display_usage();
             }
         }
diff --git a/test/dvr_segment_test/dvr_segment_test.c b/test/dvr_segment_test/dvr_segment_test.c
index e9cf253..cfddc00 100644
--- a/test/dvr_segment_test/dvr_segment_test.c
+++ b/test/dvr_segment_test/dvr_segment_test.c
@@ -28,16 +28,16 @@
   char buf[BUF_LEN];
   memset(buf, 0, BUF_LEN);
 
-  Segment_OpenParams_t rparams;
+  Segment_OpenParams_t params;
 
-  memset(rparams.location, 0, DVR_MAX_LOCATION_SIZE);
-  strncpy(rparams.location, "/data/pvr/tsthal_rec1", strlen("/data/pvr/tsthal_rec1"));
+  memset(params.location, 0, DVR_MAX_LOCATION_SIZE);
+  strncpy(params.location, "/data/pvr/test_hal_rec1", strlen("/data/pvr/test_hal_rec1"));
 
-  rparams.segment_id = (uint64_t)id;
-  rparams.mode = SEGMENT_MODE_READ;
+  params.segment_id = (uint64_t)id;
+  params.mode = SEGMENT_MODE_READ;
   printf("start open segment read mode\r\n");
   //dump file len write ptr pos
-  segment_open(&rparams, &r_handle);
+  segment_open(&params, &r_handle);
   if (r_handle == NULL) {
       printf("read error\n");
       return 0;
diff --git a/test/dvr_wrapper_test/dvr_wrapper_test.c b/test/dvr_wrapper_test/dvr_wrapper_test.c
index 7ce05d4..fa86985 100644
--- a/test/dvr_wrapper_test/dvr_wrapper_test.c
+++ b/test/dvr_wrapper_test/dvr_wrapper_test.c
@@ -149,8 +149,6 @@
 #define DVR_STREAM_TYPE_TO_FMT(_t)  ((_t) & 0xFFFFFF)
 
 
-#define rec_log_printf(...) __android_log_print(ANDROID_LOG_INFO, "rec" TAG_EXT, __VA_ARGS__)
-
 #define TSP_EVT(fmt, ...)   fprintf(stdout, "TsPlayer:" fmt, ##__VA_ARGS__)
 #define REC_EVT(fmt, ...)   fprintf(stdout, "recorder:" fmt, ##__VA_ARGS__)
 #define PLAY_EVT(fmt, ...)  fprintf(stdout, "player:" fmt, ##__VA_ARGS__)
@@ -161,7 +159,7 @@
 static int vpid=0x1fff, apid=0x1fff, vfmt=0, afmt=0;
 static int duration=60;
 static int size=1024*1024*1024;
-static int tssrc=0;
+static int ts_src=0;
 static int pause=0;
 
 static int mode = 0;
@@ -186,7 +184,7 @@
     INF( "*pause\n");
     INF( "*resume\n");
     INF( "*f speed(100,200,300,-100,-200..)\n");
-    INF( "*seek time_in_msecond\n");
+    INF( "*seek time_in_ms\n");
     INF( "*aud <pid>:<fmt>\n");
     INF( "*info (print record info)\n");
     INF( "*stat (print playback status)\n");
@@ -198,7 +196,7 @@
 {
     DVR_Bool_t go = DVR_TRUE;
     char buf[256];
-    int error;
+    int error = 0;
 
     display_usage();
 
@@ -209,7 +207,7 @@
                 go = DVR_FALSE;
                 continue;
             }
-            else if (!strncmp(buf, "pause", 5)) {
+            if (!strncmp(buf, "pause", 5)) {
                 error = dvr_wrapper_pause_playback(player);
                 INF( "pause=(%d)\n", error);
             }
@@ -245,7 +243,7 @@
                 DVR_WrapperPlaybackStatus_t status;
                 INF("playback status:\n");
                 error = dvr_wrapper_get_playback_status(player, &status);
-                RESULT("state:%d\n", status.state);
+                RESULT("state:%d=(%d)\n", status.state, error);
                 RESULT("curr(time/size/pkts):%lu:%llu:%u\n",
                     status.info_cur.time,
                     status.info_cur.size,
@@ -263,7 +261,7 @@
                 INF("rec resumed.\n");
             }
             else {
-                ERR("Unkown command: %s\n", buf);
+                ERR("Unknown command: %s\n", buf);
                 display_usage();
             }
         }
@@ -308,7 +306,7 @@
               TSP_EVT("[evt] AM_TSPLAYER_EVENT_TYPE_USERDATA_AFD: %x-%x-%x-%x ,size %d\n",
                   pbuf[0], pbuf[1], pbuf[2], pbuf[3], size);
               USERDATA_AFD_t afd = *((USERDATA_AFD_t *)pbuf);
-              afd.reserved = afd.pts = 0;
+              afd.reserved = 0;
               TSP_EVT("[evt] video afd changed: flg[0x%x] fmt[0x%x]\n", afd.af_flag, afd.af);
               break;
           }
@@ -459,12 +457,12 @@
     DVR_WrapperRecordStartParams_t rec_start_params;
     DVR_WrapperPidsInfo_t *pids_info;
     char cmd[256];
-    int error;
+    int error = 0;
 
-    sprintf(cmd, "echo ts%d > /sys/class/stb/demux%d_source", tssrc, DMX_DEV_DVR);
+    sprintf(cmd, "echo ts%d > /sys/class/stb/demux%d_source", ts_src, DMX_DEV_DVR);
     //system(cmd);
     printf("set dmx source used api\r\n");
-    dvb_set_demux_source(DMX_DEV_DVR, tssrc);
+    dvb_set_demux_source(DMX_DEV_DVR, ts_src);
     memset(&rec_open_params, 0, sizeof(DVR_WrapperRecordOpenParams_t));
 
     rec_open_params.dmx_dev_id = DMX_DEV_DVR;
@@ -477,13 +475,21 @@
     if (is_timeshifting(mode))
         rec_open_params.flags |= DVR_RECORD_FLAG_ACCURATE;
 
-    strncpy(rec_open_params.location, pfilename, sizeof(rec_open_params.location));
+    const int len = strlen(pfilename);
+    if (len >= DVR_MAX_LOCATION_SIZE || len <= 0) {
+      ERR( "Invalid file name length %d\n", len);
+      return -1;
+    }
+    strncpy(rec_open_params.location, pfilename, len+1);
 
     rec_open_params.is_timeshift = (is_timeshifting(mode)) ? DVR_TRUE : DVR_FALSE;
 
     if (!(vpid > 0 && vpid < 0x1fff))
       rec_open_params.flush_size = 1024;
 
+    /* Give it false to follow old manner. Please refer to SWPL-75327*/
+    rec_open_params.force_sysclock = DVR_FALSE;
+
     error = dvr_wrapper_open_record(&recorder, &rec_open_params);
     if (error) {
       ERR( "recorder open fail = (0x%x)\n", error);
@@ -527,13 +533,17 @@
     int aid = 0x1fff, vid = 0x1fff;
     int aft = 0, vft = 0;
 
+    memset(&seg_info,0,sizeof(seg_info));
+
     error = dvr_segment_get_list(location, &segment_nb, &p_segment_ids);
     if (!error && segment_nb) {
         error = dvr_segment_get_info(location, p_segment_ids[0], &seg_info);
         free(p_segment_ids);
+        p_segment_ids = NULL;
     }
     if (!error) {
         int i;
+        // coverity[tainted_data]
         for (i = 0; i < seg_info.nb_pids; i++) {
             switch (DVR_STREAM_TYPE_TO_TYPE(seg_info.pids[i].type))
             {
@@ -575,6 +585,10 @@
     if (vfmt)
         *vfmt = vft;
 
+    if (p_segment_ids != NULL) {
+      free(p_segment_ids);
+      p_segment_ids=NULL;
+    }
     return 0;
 }
 static uint64_t dvr_time_getClock(void)
@@ -583,7 +597,7 @@
   uint64_t ms;
 
   clock_gettime(CLOCK_REALTIME, &ts);
-  ms = ts.tv_sec*1000+ts.tv_nsec/1000000;
+  ms = ts.tv_sec*1000LLU+ts.tv_nsec/1000000LLU;
   INF("dvr_time_getClock:sec:%ld.\n", ts.tv_sec);
   return ms;
 }
@@ -601,8 +615,13 @@
     play_pids.video.type = DVR_STREAM_TYPE_VIDEO;
     play_pids.audio.type = DVR_STREAM_TYPE_AUDIO;
 
+    const int len = strlen(pfilename);
+    if (len >= DVR_MAX_LOCATION_SIZE || len <= 0) {
+      ERR( "Invalid file name length %d\n", len);
+      return -1;
+    }
+    strncpy(play_params.location, pfilename, len+1);
     if (is_timeshifting(mode)) {
-        strncpy(play_params.location, pfilename, sizeof(play_params.location));
         play_params.is_timeshift = DVR_TRUE;
 
         play_pids.video.pid = vpid;
@@ -610,10 +629,13 @@
         play_pids.audio.pid = apid;
         play_pids.audio.format = afmt;
     } else {
-        strncpy(play_params.location, pfilename, sizeof(play_params.location));
         play_params.is_timeshift = DVR_FALSE;
         {
-            int vpid = 0x1fff, apid = 0x1fff, vfmt = 0, afmt = 0;
+            vpid = 0x1fff;
+            apid = 0x1fff;
+            vfmt = 0;
+            afmt = 0;
+            // coverity[format_string_injection]
             get_dvr_info(pfilename, &apid, &afmt, &vpid, &vfmt);
 
             play_pids.video.pid = vpid;
@@ -628,7 +650,8 @@
 
      /*open TsPlayer*/
     {
-       uint32_t versionM, versionL;
+       uint32_t versionM = 0;
+       uint32_t versionL = 0;
        am_tsplayer_init_params init_param =
        {
           .source = TS_MEMORY,
@@ -649,12 +672,12 @@
        INF( "open TsPlayer %s, result(%d)\n", (result)? "FAIL" : "OK", result);
 
        result = AmTsPlayer_getVersion(&versionM, &versionL);
-       INF( "TsPlayer verison(%d.%d) %s, result(%d)\n",
+       INF( "TsPlayer version(%d.%d) %s, result(%d)\n",
           versionM, versionL,
           (result)? "FAIL" : "OK",
           result);
 
-       result = AmTsPlayer_registerCb(tsplayer_handle,
+       AmTsPlayer_registerCb(tsplayer_handle,
           tsplayer_callback,
           "tsp0");
 
@@ -681,7 +704,7 @@
        INF( "Starting playback\n");
        int time = dvr_time_getClock();
        INF( "Starting playback time:%d\n", time);
-	    //error = dvr_wrapper_setlimit_playback(player, time - 110*60*1000, 90*60*1000);
+        //error = dvr_wrapper_setlimit_playback(player, time - 110*60*1000, 90*60*1000);
         error = dvr_wrapper_start_playback(player, play_flag, &play_pids);
        if (error)
        {
@@ -753,7 +776,7 @@
         else if (!strncmp(argv[i], "size", 4))
             sscanf(argv[i], "size=%i", &size);
         else if (!strncmp(argv[i], "tsin", 4))
-            sscanf(argv[i], "tsin=%i", &tssrc);
+            sscanf(argv[i], "tsin=%i", &ts_src);
         else if (!strncmp(argv[i], "pause", 5))
             sscanf(argv[i], "pause=%i", &pause);
         else if (!strncmp(argv[i], "file", 4))
@@ -797,7 +820,7 @@
     if (!mode) {
         mode = TIMESHIFTING;
         INF( " timeshifting");
-        pfilename = pfilename;
+        pfilename = rec_filename;
     }
 
     INF( " 0x%x\n", mode);
@@ -806,7 +829,7 @@
         INF( "video:%d:%d(pid/fmt) audio:%d:%d(pid/fmt)\n",
             vpid, vfmt, apid, afmt);
         INF( "duration:%d size:%d tsin:%d\n",
-            duration, size, tssrc);
+            duration, size, ts_src);
         if (!is_timeshifting(mode)) {
             INF( "recording file:%s\n",
                 pfilename);
@@ -822,11 +845,19 @@
             pause);
     }
 
-    if (has_recording(mode))
+    if (has_recording(mode)) {
         error = start_recording();
+        if (error != 0) {
+          ERR("start_recording failed with return value %d",error);
+        }
+    }
 
-    if (is_playback(mode))
+    if (is_playback(mode)) {
         error = start_playback(0, 0, 0, 0);
+        if (error != 0) {
+          ERR("start_playback failed with return value %d",error);
+        }
+    }
 
     if (is_timeshifting(mode))
         playback_pending = 1;
diff --git a/test/dvr_write_test/dvr_write_test.c b/test/dvr_write_test/dvr_write_test.c
index e54c8e6..7bee740 100644
--- a/test/dvr_write_test/dvr_write_test.c
+++ b/test/dvr_write_test/dvr_write_test.c
@@ -1,13 +1,13 @@
-#include <stdio.h> 
+#include <stdio.h>
 #include <sys/time.h>
 #include <fcntl.h>
 #include <sys/types.h>
 #include <stddef.h>
 #include <unistd.h>
 
-#define ONCE_WRITE_SIZE (256 * 1024)	
-#define WRITE_TOTAL_SIZE (100*1024*1024)
- 
+#define ONCE_WRITE_SIZE (256 * 1024)
+#define WRITE_TOTAL_SIZE (100 * 1024 * 1024)
+
 /* Define NULL pointer value and the offset() macro */
 #ifndef NULL
 #define NULL ((void *)0)
@@ -20,45 +20,52 @@
 
 int main(int argc, char **argv)
 {
-	char * Filename = "arecord.data";
-	int ts_fd = -1;
-	int ret = 0;
+    char * Filename = "arecord.data";
+    int ret = 0;
 
-	struct timeval t1, t2;
-	struct timeval beginTime, endTime;
-	char data[ONCE_WRITE_SIZE] = {'1'} ;
+    struct timeval t1, t2;
+    struct timeval beginTime, endTime;
+    char *data;
 
-	if (argc > 1)  {
-		Filename = argv[1];
-		printf("filename: %s \n",Filename);		
-	}	
+    if (argc > 1)  {
+        Filename = argv[1];
+        printf("filename: %s \n",Filename);
+    }
 
-	ts_fd = open(Filename, O_CREAT | O_RDWR | O_TRUNC , 0644);	
+    // coverity[path_manipulation_sink]
+    int ts_fd = open(Filename, O_CREAT | O_RDWR | O_TRUNC , 0644);
         if (ts_fd < 0) {
-		printf("open %s failed\n",Filename);
-		return -1;
-	}	
-	
-	int write_count  = WRITE_TOTAL_SIZE / ONCE_WRITE_SIZE;
-	
-	gettimeofday(& beginTime, NULL);
-	for(int i = 0; i < write_count;  i++) {
-		gettimeofday(& t1, NULL);
-		ret = write(ts_fd,data, ONCE_WRITE_SIZE);
-		fsync(ts_fd);
-		gettimeofday(& t2, NULL);
-		if (ret != 0) {
-			printf("%d: write %d data cost : %dms Bitrate: %d m bps\n", i, ret,get_diff_time(t1,t2), ONCE_WRITE_SIZE*(8*1000)/1024/1024/get_diff_time(t1,t2));
-		};
-	}
-	gettimeofday(& endTime, NULL);
-	close(ts_fd);
-	ts_fd = -1;
-	printf("write over, check data now\n");
-	printf("TotalSize %dm,cost total Time: %dms\n", WRITE_TOTAL_SIZE/1024/1024, get_diff_time(beginTime,endTime));
-	
-	printf("Bitrate %dm bps\n", WRITE_TOTAL_SIZE/1024/1024*8*1000/get_diff_time(beginTime,endTime));
-	
-	return 0;
-	
+        printf("open %s failed\n",Filename);
+        return -1;
+    }
+
+    int write_count  = WRITE_TOTAL_SIZE / ONCE_WRITE_SIZE;
+
+    data = malloc(ONCE_WRITE_SIZE);
+    if (data == NULL) {
+        printf("Failed to allocate memory");
+        close(ts_fd);
+        return -1;
+    }
+    memset(data,1,ONCE_WRITE_SIZE);
+
+    gettimeofday(&beginTime, NULL);
+    for (int i = 0; i < write_count;  i++) {
+        gettimeofday(&t1, NULL);
+        ret = write(ts_fd, data, ONCE_WRITE_SIZE);
+        fsync(ts_fd);
+        gettimeofday(&t2, NULL);
+        if (ret != 0) {
+            printf("%d: write %d data cost : %dms Bitrate: %d m bps\n",
+            i, ret, get_diff_time(t1, t2), ONCE_WRITE_SIZE * (8 * 1000) / 1024 / 1024 / get_diff_time(t1, t2));
+        };
+    }
+    gettimeofday(&endTime, NULL);
+    close(ts_fd);
+    printf("write over, check data now\n");
+    printf("TotalSize %dm,cost total Time: %dms\n", WRITE_TOTAL_SIZE / 1024 / 1024, get_diff_time(beginTime, endTime));
+    printf("Bitrate %dm bps\n", WRITE_TOTAL_SIZE / 1024 /1024 * 8 * 1000 / get_diff_time(beginTime, endTime));
+
+    free(data);
+    return 0;
 }