tinyalsa剖析

一代枭雄 / 2023-08-28 / 原文

external/tinyalsa/

  

/external/tinyalsa/include/tinyalsa/

在该目录下,仅存在一个asoundlib.h的头文件,这个文件应该是向hal层提供一些接口。

1. Android.bp

查看代码
cc_library {
   name: "libtinyalsa",
   host_supported: true,
   vendor_available: true,
   vndk: {
       enabled: true,
   },
   srcs: [
       "mixer.c",
        "pcm.c",
    ],
    cflags: ["-Werror", "-Wno-macro-redefined"],
    export_include_dirs: ["include"],
    local_include_dirs: ["include"],

    target: {
        darwin: {
            enabled: false,
        },
    },
}

cc_binary {
    name: "tinyplay",
    host_supported: true,
    srcs: ["tinyplay.c"],
    shared_libs: ["libtinyalsa"],
    cflags: ["-Werror"],
    target: {
        darwin: {
            enabled: false,
        },
    },
}

cc_binary {
    name: "tinycap",
    srcs: ["tinycap.c"],
    shared_libs: ["libtinyalsa"],
    cflags: ["-Werror"],
}

cc_binary {
    name: "tinymix",
    srcs: ["tinymix.c"],
    shared_libs: ["libtinyalsa"],
    cflags: ["-Werror", "-Wall"],
}

cc_binary {
    name: "tinyhostless",
    srcs: ["tinyhostless.c"],
    shared_libs: ["libtinyalsa"],
    cflags: ["-Werror"],
}

cc_binary {
    name: "tinypcminfo",
    srcs: ["tinypcminfo.c"],
    shared_libs: ["libtinyalsa"],
    cflags: ["-Werror"],
}

该Android.bp文件向外界提供了:

1)提供了libtinyalsa库,个人认为还是hal层直接调用。通过这个库调用到底层。该库是由源文件pcm.c和mixer.c生成;

2)提供了tinyplay, tinycap, tinymix, tinyhostless, tinypcminfo等可执行程序,这些程序仅仅是为了测试。

2. tinyplay程序分析

#include <tinyalsa/asoundlib.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <signal.h>

#define ID_RIFF 0x46464952
#define ID_WAVE 0x45564157
#define ID_FMT  0x20746d66
#define ID_DATA 0x61746164

//WAV文件遵循RIFF规则,其内容以区块(chunk)为最小单位进行存储。
//chunk就有id和size

struct riff_wave_header {
    uint32_t riff_id; //riff_id 固定死,填入 RIFF 
    uint32_t riff_sz; //riff_sz 为文件长度减去 ID 和 Size 的长度,即 fileSize - 8
    uint32_t wave_id; //如果wave_id是wav,表示后面有 Format chunk 和 Data chunk。
};

//每一个chunk都有id和size.
//id是以大端进行存储的。
struct chunk_header {
    uint32_t id;
    uint32_t sz;
};

struct chunk_fmt {
    uint16_t audio_format;//音频格式
    uint16_t num_channels; //通道数
    uint32_t sample_rate;  //采样率
    uint32_t byte_rate;    //传输速率,每秒的字节数。计算公式为:sample_rate*num_channels*bits_per_sample/8
    uint16_t block_align;  //块对齐,告知播放软件一次需要处理多少字节。公式为bits_per_sample*num_channels/8
    uint16_t bits_per_sample;//采样位数,一般有8/16/24/32/64,值越大,对声音的还原度越高
};

static int close = 0;

void play_sample(FILE *file, unsigned int card, unsigned int device, unsigned int channels,
                 unsigned int rate, unsigned int bits, unsigned int period_size,
                 unsigned int period_count);

void stream_close(int sig)
{
    /* allow the stream to be closed gracefully */
    signal(sig, SIG_IGN);
    close = 1;
}

int main(int argc, char **argv)
{
    FILE *file;
    struct riff_wave_header riff_wave_header;
    struct chunk_header chunk_header;
    struct chunk_fmt chunk_fmt;
    unsigned int device = 0;
    unsigned int card = 0;
    unsigned int period_size = 1024;  //一个period中有1024个帧
    unsigned int period_count = 4;    //缓冲区的大小为4个period_size的大小
    char *filename;
    int more_chunks = 1;

    if (argc < 2) { //参数不能少于2个
        fprintf(stderr, "Usage: %s file.wav [-D card] [-d device] [-p period_size]"
                " [-n n_periods] \n", argv[0]);
        return 1;
    }

    filename = argv[1];  //文件名称
    file = fopen(filename, "rb"); //打开文件
    if (!file) {
        fprintf(stderr, "Unable to open file '%s'\n", filename);
        return 1;
    }

    //从file中读取1个对象,该对象的大小为sizeof(riff_wave_header),即12个字节
    fread(&riff_wave_header, sizeof(riff_wave_header), 1, file);
    
    //头部必须是RIFF, type必须是wave
    if ((riff_wave_header.riff_id != ID_RIFF) ||
        (riff_wave_header.wave_id != ID_WAVE)) {
        fprintf(stderr, "Error: '%s' is not a riff/wave file\n", filename);
        fclose(file);
        return 1;
    }

    do {
        //这个地方的思想就是通过id来找format chunk和data chunk,当找到的id不是这两个之一,
        //那么就会利用fseek跳过chunk_header.size
        
        //对于第一次循环,做注释
        //此时的fseek指针为0+12个字节处。从目前fseek指向的地址处,读取1个对象
        //该对象的大小为sizeof(chunk_header),即为8
        
        //第二次循环:我们假设上一次已经找到了format_chunk,接下来就是找取data_chunk的过程了。
        fread(&chunk_header, sizeof(chunk_header), 1, file);

        switch (chunk_header.id) {
        case ID_FMT: 
            //此时fseek指向0+12+8处,从fseek指向的地址处,读取1个对象,
            //该对象的大小为sizeof(chunk_fmt),即16个字节。
            fread(&chunk_fmt, sizeof(chunk_fmt), 1, file);
            /* If the format header is larger, skip the rest */
            //一般来说chunk_header.size的大小等于chunk_fmt的大小,但是不能排除特殊情况。如果大于,那么使fseek跳过
            //多余的那些字节。为什么会这么处理呢?因为我们已经获取到了音频文件的格式,如声道数、采样率等等。接下来,
            //我们需要找到data所在的chunk.
            if (chunk_header.sz > sizeof(chunk_fmt))
                fseek(file, chunk_header.sz - sizeof(chunk_fmt), SEEK_CUR);
            break;
        case ID_DATA:
            /* Stop looking for chunks */
            more_chunks = 0;  //一旦找到了data_chunk,那么将该变量置0.说明,我们不需要下一次循环了。接下里处理数据就好了
            break;
        default:
            /* Unknown chunk, skip bytes */
            fseek(file, chunk_header.sz, SEEK_CUR);
        }
    } while (more_chunks); //第一次循环时,more_chunks为1,那么接下来进行第二次循环

    /* parse command line arguments */
    argv += 2; //如果直接调用tinyplay a.wav,那么只存在argv[0] = tinyplay, argv[1] = a.wav
    while (*argv) {
        if (strcmp(*argv, "-d") == 0) {
            argv++;
            if (*argv)
                device = atoi(*argv);
        }
        if (strcmp(*argv, "-p") == 0) {
            argv++;
            if (*argv)
                period_size = atoi(*argv);
        }
        if (strcmp(*argv, "-n") == 0) {
            argv++;
            if (*argv)
                period_count = atoi(*argv);
        }
        if (strcmp(*argv, "-D") == 0) {
            argv++;
            if (*argv)
                card = atoi(*argv);
        }
        if (*argv)
            argv++;
    }

    play_sample(file, card, device, chunk_fmt.num_channels, chunk_fmt.sample_rate,
                chunk_fmt.bits_per_sample, period_size, period_count);

    fclose(file);

    return 0;
}

int check_param(struct pcm_params *params, unsigned int param, unsigned int value,
                 char *param_name, char *param_unit)
{
    unsigned int min;
    unsigned int max;
    int is_within_bounds = 1;

    min = pcm_params_get_min(params, param);
    if (value < min) {
        fprintf(stderr, "%s is %u%s, device only supports >= %u%s\n", param_name, value,
                param_unit, min, param_unit);
        is_within_bounds = 0;
    }

    max = pcm_params_get_max(params, param);
    if (value > max) {
        fprintf(stderr, "%s is %u%s, device only supports <= %u%s\n", param_name, value,
                param_unit, max, param_unit);
        is_within_bounds = 0;
    }

    return is_within_bounds;
}

int sample_is_playable(unsigned int card, unsigned int device, unsigned int channels,
                        unsigned int rate, unsigned int bits, unsigned int period_size,
                        unsigned int period_count)
{
    struct pcm_params *params;
    int can_play;

    params = pcm_params_get(card, device, PCM_OUT);
    if (params == NULL) {
        fprintf(stderr, "Unable to open PCM device %u.\n", device);
        return 0;
    }

    can_play = check_param(params, PCM_PARAM_RATE, rate, "Sample rate", "Hz");
    can_play &= check_param(params, PCM_PARAM_CHANNELS, channels, "Sample", " channels");
    can_play &= check_param(params, PCM_PARAM_SAMPLE_BITS, bits, "Bitrate", " bits");
    can_play &= check_param(params, PCM_PARAM_PERIOD_SIZE, period_size, "Period size", " frames");
    can_play &= check_param(params, PCM_PARAM_PERIODS, period_count, "Period count", " periods");

    pcm_params_free(params);

    return can_play;
}

void play_sample(FILE *file, unsigned int card, unsigned int device, unsigned int channels,
                 unsigned int rate, unsigned int bits, unsigned int period_size,
                 unsigned int period_count)
{
    struct pcm_config config;
    struct pcm *pcm;
    char *buffer;
    int size;
    int num_read;

    memset(&config, 0, sizeof(config));
    config.channels = channels;
    config.rate = rate;
    config.period_size = period_size;
    config.period_count = period_count;
    if (bits == 32)
        config.format = PCM_FORMAT_S32_LE;
    else if (bits == 24)
        config.format = PCM_FORMAT_S24_3LE;
    else if (bits == 16)
        config.format = PCM_FORMAT_S16_LE;
    config.start_threshold = 0;
    config.stop_threshold = 0;
    config.silence_threshold = 0;

    if (!sample_is_playable(card, device, channels, rate, bits, period_size, period_count)) {
        return;
    }

    pcm = pcm_open(card, device, PCM_OUT, &config);
    if (!pcm || !pcm_is_ready(pcm)) {
        fprintf(stderr, "Unable to open PCM device %u (%s)\n",
                device, pcm_get_error(pcm));
        return;
    }

    size = pcm_frames_to_bytes(pcm, pcm_get_buffer_size(pcm));
    buffer = malloc(size);
    if (!buffer) {
        fprintf(stderr, "Unable to allocate %d bytes\n", size);
        free(buffer);
        pcm_close(pcm);
        return;
    }

    printf("Playing sample: %u ch, %u hz, %u bit\n", channels, rate, bits);

    /* catch ctrl-c to shutdown cleanly */
    signal(SIGINT, stream_close);

    do {
        num_read = fread(buffer, 1, size, file);
        if (num_read > 0) {
            if (pcm_write(pcm, buffer, num_read)) {
                fprintf(stderr, "Error playing sample\n");
                break;
            }
        }
    } while (!close && num_read > 0);

    free(buffer);
    pcm_close(pcm);
}