📄 mymad.c
字号:
#include <stdio.h>#include <stdlib.h>#include <errno.h>#include <syslog.h>#include <string.h>#include <unistd.h>#include <sys/stat.h>#include <fcntl.h>#include <sys/types.h>#include <sys/socket.h>#include <netinet/in.h>#include <netdb.h>#include <arpa/inet.h>#include "mad.h"#include "mymad.h"enum mad_flow input(void *data, struct mad_stream *stream){ struct buffer *madbuf = data; ssize_t nreads = 0; int bytes_left = stream->bufend - stream->next_frame; if(madbuf->finished) return MAD_FLOW_STOP; if(madbuf->buf == NULL) { err_cont("no space allocated for buf, error in input callback function"); return MAD_FLOW_STOP; } if (bytes_left) { /* data remain in stream */ memmove(madbuf->buf, stream->next_frame, bytes_left); madbuf->length += bytes_left; } if (nreads = recv(madbuf->sockfd, madbuf->buf + bytes_left, (MAD_BUF_SIZE - bytes_left), 0) > 0) { madbuf->length += nreads; } else madbuf->finished = 1; mad_stream_buffer(stream, madbuf->buf, MAD_BUF_SIZE); return MAD_FLOW_CONTINUE;}inlinesigned int scale(mad_fixed_t sample){ /* round */ sample += (1L << (MAD_F_FRACBITS - 16)); /* clip */ if (sample >= MAD_F_ONE) sample = MAD_F_ONE - 1; else if (sample < -MAD_F_ONE) sample = -MAD_F_ONE; /* quantize */ return sample >> (MAD_F_FRACBITS + 1 - 16);}enum mad_flow output(void *data, struct mad_header const *header, struct mad_pcm *pcm){ unsigned int rate; unsigned short nchannels, nsamples; mad_fixed_t const *left_ch, *right_ch; nchannels = pcm->channels; nsamples = pcm->length; left_ch = pcm->samples[0]; right_ch = pcm->samples[1]; /* buffer hold the output PCM data */ static unsigned char stream[1152*4]; signed int sample; char * ptr = stream; while (nsamples--) { /* output sample(s) in 16-bit signed little-endian PCM */ sample = scale(*left_ch++); *ptr++ = ((sample >> 0) & 0xff); *ptr++ = ((sample >> 8) & 0xff); if (nchannels == 2) { sample = scale(*right_ch++); *ptr++ = ((sample >> 0) & 0xff); *ptr++ = ((sample >> 8) & 0xff); } } /* pass PCM data to alsa */ alsa_play(stream, ((pcm->length) * 4)); return MAD_FLOW_CONTINUE;}enum mad_flow error(void *data, struct mad_stream *stream, struct mad_frame *frame){ return MAD_FLOW_CONTINUE;}int mad(int sockfd){ static struct buffer madbuf; static struct mad_decoder decoder; int ret_val; alsa_init(); alsa_config(); /* initialize structure buffer */ madbuf.buf = malloc(MAD_BUF_SIZE); madbuf.length = 0; madbuf.sockfd = sockfd; madbuf.finished = 0; /* configure input, output, and error functions */ mad_decoder_init(&decoder, &madbuf, input, 0 /* header */, 0 /* filter */, output, error, 0 /* message */); /* start decoding */ ret_val = mad_decoder_run(&decoder, MAD_DECODER_MODE_SYNC); /* release the decoder */ mad_decoder_finish(&decoder); /* release the madbuf->buf */ free(madbuf.buf); /* close the PCM device */ alsa_finish(); return ret_val;}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -