首页 > 其他分享 >tinyalsa剖析

tinyalsa剖析

时间:2023-08-27 22:56:19浏览次数:39  
标签:int tinyalsa chunk unsigned argv 剖析 header file

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);
}

 

标签:int,tinyalsa,chunk,unsigned,argv,剖析,header,file
From: https://www.cnblogs.com/-glb/p/17661044.html

相关文章

  • 第四节:分库分表深度剖析
    一.        二.        三.         !作       者:Yaopengfei(姚鹏飞)博客地址:http://www.cnblogs.com/yaopengfei/声     明1:如有错误,欢迎讨论,请勿谩骂^_^。声     明2:原创博客请在转载......
  • JVM对象创建与内存分配机制深度剖析
    对象的创建对象创建的主要流程: 1.类加载检查 虚拟机遇到一条new指令时,首先将去检查这个指令的参数是否能在常量池中定位到一个类的符号引用,并且检查这个符号引用代表的类是否已被加载、解析和初始化过。如果没有,那必须先执行相应的类加载过程。 new指令对应到语言层......
  • 《深入浅出Java虚拟机 — JVM原理与实战》带你攻克技术盲区,夯实底层基础 —— 吃透cla
    前言介绍了解Java代码如何编译成字节码并在JVM上执行是非常重要的。这种理解可以帮助我们理解程序执行时发生的情况,确保语言特性符合逻辑,并在进行讨论时能够全面考虑各种因素和副作用。本文将深入探讨Java代码编译成字节码并在JVM上执行的过程。如果您对JVM的内部结构和字节码执行......
  • JVM内存模型深度剖析与优化
    JDK体系结构Java语言的跨平台特性JVM整体结构及内存模型 二、JVM内存参数设置 SpringBoot程序的JVM参数设置格式(Tomcat启动直接加在bin目录下catalina.sh文件里):java‐Xms2048M‐Xmx2048M‐Xmn1024M‐Xss512K‐XX:MetaspaceSize=256M‐XX:MaxMetaspaceSize=25......
  • 从JDK源码级别彻底剖析JVM类加载机制
    类加载运行全过程当我们用java命令运行某个类的main函数启动程序时,首先需要通过类加载器把主类加载到JVM。publicclassMath{publicstaticfinalintinitData=666;publicstaticUseruser=newUser();publicintcompute(){//一个方法对应一块栈帧......
  • 剖析MongoDB数据库:理解NoSQL设计模式、优化查询性能和数据安全性
    MongoDB是一个流行的NoSQL文档数据库,它使用JSON样式的文档存储数据。本文将对MongoDB进行剖析,包括NoSQL设计模式、优化查询性能和数据安全性。NoSQL设计模式文档数据库MongoDB采用文档数据库的设计模式,即将相关数据保存在单个文档中,而不是将其拆分成多个表。这种设计模式使得数......
  • 分布式存储系统举例剖析(elasticsearch,kafka,redis-cluster)
    1.概述对于分布式系统,人们首先对现实中的分布式系统进行高层抽象,然后做出各种假设,发展了诸如CAP,FLP等理论,提出了很多一致性模型,Paxos是其中最璀璨的明珠。我们对分布式系统的时序,复制模式,一致性等基础理论特别关注。在共识算法的基础上衍生了选举算法,并且为分布式事务提供......
  • 普通二叉搜索树剖析
    二叉搜索树概述二叉搜索树是一种具有特殊性质的二叉树。二叉搜索树可以是一棵空树,若不为空树,其:若左子树不为空,则左子树所有的节点值小于根节点值;若右子树不为空,则右子树所有的节点值大于根节点值。与二叉树一样,二叉搜索树也是递归定义的,二叉搜索树的左右子树都是二叉搜索树。二叉搜......
  • 深度剖析:内部威胁监测中的 ADAudit Plus 关键作用
    在数字时代,企业不仅需要抵御外部威胁,还必须密切关注内部威胁,因为内部因素可能对数据安全造成严重威胁。作为一种强大的内部威胁监测工具,ADAuditPlus在这一领域发挥着关键作用。本文将深入探讨ADAuditPlus在内部威胁监测中的重要性以及其特点。内部威胁一、内部威胁的隐患内部......
  • 字符串函数剖析(3)---strstr函数
    1.strstr函数的巧妙--查找子字符串1.1模拟实现strstr函数strstr函数:在一个字符串中查找子串学习新函数时,先去c库查找该函数的相关资料,更加助于你的学习constchar*strstr(constchar*str1,constchar*str2);先看函数的声明,参数是两个地址,不可更改。先看看strstr函数......