#include <stdlib.h>
#include "hal_interface_audio.h"
#include "list.h"
#include "htime.h"
#include "hthread.h"
#include "hbase.h"
#include "hlog.h"
#include "hmutex.h"

typedef struct{
	struct list_head    link;
	HAL_AUDIO_FORMAT    format;
	hal_audio_frame_callback cb;
}audio_ins;

static struct list_head s_alist = LIST_HEAD_INIT(s_alist);

uint32_t hal_audio_openstream(hal_audio_frame_callback cb, HAL_AUDIO_FORMAT format){
	struct list_head *pos, *n;
	list_for_each_safe(pos, n, &s_alist){
		audio_ins* audio = list_entry(pos, audio_ins, link);
        if (audio->cb == cb) {
		   return 0;
        }
	}
	audio_ins *audio = (audio_ins*)hv_malloc(sizeof(audio_ins));
	if (!audio){
		hloge("%s failed to hv_malloc", __func__);
		return -1;
	}
	audio->cb     = cb;
	audio->format = format;
	list_add_tail(&audio->link, &s_alist);
	return 0;
}

uint32_t hal_audio_closestream(hal_audio_frame_callback cb){
	struct list_head *pos, *n;
	list_for_each_safe(pos, n, &s_alist){
		audio_ins* audio = list_entry(pos, audio_ins, link);
        if (audio->cb == cb) {
           list_del(pos);
		   hv_free(audio);
		   return 0;
        }
	}
	return -1;
}

static void * audio_polling_task(void *arg)
{
	uint32_t ret;
	typedef struct{
		int8_t  *data;
		int16_t  size;
	}aac_st;
	while(1){
		audio_frame frame;
		ret = hal_audio_get_frame(&frame);
		if (ret == 0){
			aac_st aac = {0};
			struct list_head *pos, *n;
			list_for_each_safe(pos, n, &s_alist){
				audio_ins* audio = list_entry(pos, audio_ins, link);
				frame.format = audio->format;
				switch(audio->format){
					case HAL_AUDIO_PCM:
						audio->cb(&frame);
						break;
					case HAL_AUDIO_AAC_LC:{
							if (aac.data == NULL){
								//encode aac ......
							}
							if (aac.data && aac.size){
								memcpy(frame.data, aac.data, aac.size);
								frame.size = aac.size;
								audio->cb(&frame);
							}
							
						}break;
					default:
						break;
				}
			}
		}
	}
}
