<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Justme0 的博客</title>
    <description>撷英采华，以备不需</description>
    <link>https://justme0.com/</link>
    <atom:link href="https://justme0.com/feed.xml" rel="self" type="application/rss+xml" />
    <pubDate>Sun, 07 Jun 2026 15:15:43 +0000</pubDate>
    <lastBuildDate>Sun, 07 Jun 2026 15:15:43 +0000</lastBuildDate>
    <generator>Jekyll v3.10.0</generator>
    
      <item>
        <title>大模型 ASR 语音识别过程分析</title>
        <description>&lt;p&gt;Qwen3 在2026年初开源了ASR语音识别模型，据官方称是state-of-the-art效果，引起Redis作者antirez的注意，他用C语言重写了语音识别推理的代码[1]，这个项目第三方依赖很少，通过它可以方便地理解大模型语音识别的过程。&lt;/p&gt;

&lt;p&gt;下面是在CPU上测试一段12.76s的音频文件离线识别的耗时分布，可以大致了解各阶段的消耗占比。&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Phase&lt;/th&gt;
      &lt;th&gt;Time&lt;/th&gt;
      &lt;th&gt;%&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Tokenizer load (vocab.json)&lt;/td&gt;
      &lt;td&gt;76ms&lt;/td&gt;
      &lt;td&gt;1.4%&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Mel spectrogram (1276 frames)&lt;/td&gt;
      &lt;td&gt;30ms&lt;/td&gt;
      &lt;td&gt;0.5%&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Encoder&lt;/strong&gt; (166 tokens)&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;2370ms&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;42.6%&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Prefill&lt;/strong&gt; (181 tokens into KV cache)&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;2352ms&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;42.2%&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Decode&lt;/strong&gt; (21 tokens, 34.3ms/tok)&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;720ms&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;12.9%&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Overhead&lt;/td&gt;
      &lt;td&gt;~20ms&lt;/td&gt;
      &lt;td&gt;0.4%&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Real-time factor: 5.57s / 12.76s = &lt;strong&gt;0.44&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;涉及代码中的主要函数&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;qwen_transcribe_audio
  transcribe_segment
    qwen_mel_spectrogram
    qwen_encoder_forward
    qwen_decoder_prefill
    qwen_decoder_forward
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;source: &lt;a href=&quot;https://sourcegraph.com/r/github.com/antirez/qwen-asr@main/-/blob/qwen_asr.c?L590&quot; target=&quot;_blank&quot;&gt;https://sourcegraph.com/r/github.com/antirez/qwen-asr@main/-/blob/qwen_asr.c?L590&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;下面将介绍以上运行过程，标题后面的百分比是耗时占比，有的细节没有展开说，只记录了要点，主要是我的笔记，重点讲解大模型 Transformer 架构。&lt;/p&gt;

&lt;h1 id=&quot;1-音频预处理pcm变换为频谱-1&quot;&gt;1. 音频预处理(PCM变换为频谱) 1%&lt;/h1&gt;

&lt;p&gt;过程：预加重、分帧、加窗；短时FFT；Mel滤波。&lt;/p&gt;

&lt;p&gt;分帧：每帧25ms，为防止割裂保持平滑性，取帧时与前后帧边界重叠，&lt;span style=&quot;color: red;&quot;&gt;  窗口每次移动10ms&lt;/span&gt;，所以 100 frames/s。&lt;/p&gt;

&lt;!-- more --&gt;

&lt;p&gt;短时FFT：重点，&lt;span style=&quot;color: red;&quot;&gt; 将窗口内时域转为频域&lt;/span&gt;。&lt;/p&gt;

&lt;p&gt;Mel刻度：音高与频率是对数关系，符合人耳听觉。来自心理学中的Weber-Fechner定律（也称对数定律），除了听觉音高，还适用于听觉响度、味觉、触觉等。&lt;/p&gt;

\[mel(f) = 2595 \space log_{10}{(1 + f/700)}\]

&lt;p&gt;1000以下近似线性，以上对数关系。&lt;/p&gt;

&lt;div align=&quot;center&quot;&gt;
&lt;img src=&quot;../assets/pic/asr/mel.png&quot; alt=&quot;mel&quot; width=&quot;900&quot; /&gt;
&lt;p&gt;mel刻度&lt;/p&gt;
&lt;/div&gt;

&lt;div align=&quot;center&quot;&gt;
&lt;img src=&quot;../assets/pic/asr/mel.webp&quot; alt=&quot;spectrom_zh.png&quot; width=&quot;900&quot; /&gt;
&lt;p&gt;语谱图&lt;/p&gt;
&lt;/div&gt;

&lt;h2 id=&quot;fbank&quot;&gt;FBank&lt;/h2&gt;
&lt;p&gt;取能量谱，经mel滤波器组滤波，将频率范围按对数方式划分为n段，人耳感觉到每段的音高差异相同，得到FBank。&lt;/p&gt;

\[E_k=\sum_{f}|X(f)|^2 H_k(f)\]

&lt;p&gt;其中 $X(f)$是频率点的幅度，$ H_k(f) $是三角滤波器权重，k是mel bin序号，从0到n-1。&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Bin 0:    20 -   45 Hz   (low bass)
Bin 1:    45 -   71 Hz
Bin 2:    71 -   98 Hz
...
Bin 60:  1000 - 1100 Hz  (mid, speech fundamentals)
...
Bin 127: 7200 - 8000 Hz  (high, sibilants like &quot;s&quot;, &quot;t&quot;)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h1 id=&quot;2-encode-43&quot;&gt;2. Encode 43%&lt;/h1&gt;
&lt;div class=&quot;language-c highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;    &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;enc_seq_len&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;kt&quot;&gt;float&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;enc_output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;qwen_encoder_forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ctx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mel_frames&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;enc_seq_len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;source: &lt;a href=&quot;https://sourcegraph.com/r/github.com/antirez/qwen-asr@b00b789b17051aea61e9717458171100662318a4/-/blob/qwen_asr.c?L612&quot; target=&quot;_blank&quot;&gt;https://sourcegraph.com/r/github.com/antirez/qwen-asr@b00b789b17051aea61e9717458171100662318a4/-/blob/qwen_asr.c?L612&lt;/a&gt;&lt;/p&gt;

&lt;h2 id=&quot;21-conv2d-22&quot;&gt;2.1 Conv2D 22%&lt;/h2&gt;

&lt;p&gt;将FBank下采样（压缩），减少数据量。&lt;/p&gt;

&lt;p&gt;使用卷积kernel（也称channel/filter/mask）提取特征，一种kernel负责提取一种特征。&lt;/p&gt;

&lt;p&gt;Why Compress:&lt;/p&gt;

&lt;p&gt;The transformer’s attention is $O(n^2)$. Processing all 1,276 mel frames directly:&lt;/p&gt;

&lt;p&gt;mel frame: 1,276 × 1,276 = 1,628,176 attention pairs  ← expensive!
token: 166 × 166 = 27,556 attention pairs  ← 59× cheaper!&lt;/p&gt;

&lt;p&gt;The Conv2D stem compresses 8× (1,276 → 166) while preserving the important speech information. The 3 Conv2D layers learn what to keep and what to discard — they keep &lt;span style=&quot;color: red;&quot;&gt; phoneme boundaries, formant transitions, and pitch changes&lt;/span&gt;, while discarding redundant information between adjacent frames. [5]&lt;/p&gt;

\[\text{Edge detector} = \begin{bmatrix} -1 &amp;amp; -1 &amp;amp; -1 \\ -1 &amp;amp; 8 &amp;amp; -1 \\ -1 &amp;amp; -1 &amp;amp; -1 \end{bmatrix}\]

\[\text{Blur} = \begin{bmatrix} \frac{1}{9} &amp;amp; \frac{1}{9} &amp;amp; \frac{1}{9} \\ \frac{1}{9} &amp;amp; \frac{1}{9} &amp;amp; \frac{1}{9} \\ \frac{1}{9} &amp;amp; \frac{1}{9} &amp;amp; \frac{1}{9} \end{bmatrix}\]

\[\text{Sharpen} = \begin{bmatrix} 0 &amp;amp; -1 &amp;amp; 0 \\ -1 &amp;amp; 5 &amp;amp; -1 \\ 0 &amp;amp; -1 &amp;amp; 0 \end{bmatrix}\]

&lt;p&gt;考察1s音频：&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;时间轴：100 mel frame 经3次卷积变为13，每一次卷积减半后取上整。（12.76s是12*13+10=166个token）&lt;/li&gt;
  &lt;li&gt;频率轴：480 kernel；128 mel bin 经3次卷积变为 16。相乘是7680。将7680压缩至896：
    &lt;div class=&quot;language-c highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;  &lt;span class=&quot;c1&quot;&gt;// qwen_asr_encoder.c&lt;/span&gt;
  &lt;span class=&quot;cm&quot;&gt;/* Project: [w3, 7680] -&amp;gt; [w3, d_model] (no bias) */&lt;/span&gt;
  &lt;span class=&quot;kt&quot;&gt;float&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;projected&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;size_t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;token_offset&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;qwen_linear_nobias&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;projected&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;reshaped&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;enc&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv_out_weight&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                   &lt;span class=&quot;n&quot;&gt;w3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;conv_proj_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
  &lt;span class=&quot;c1&quot;&gt;//                  ↑    ↑              ↑&lt;/span&gt;
  &lt;span class=&quot;c1&quot;&gt;//              13 tokens  7680 input    896 output&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;    &lt;/div&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;enc-&amp;gt;conv_out_weight&lt;/code&gt; is the [7680, 896] matrix, loaded from &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;thinker.audio_tower.conv_out.weight&lt;/code&gt; in the safetensors file. These 6.8 million weights were learned during training.&lt;/p&gt;

&lt;p&gt;考察单个token的变换如下(注意代码和论文中的向量是横向量，线性代数教科书中的向量通常是列向量)&lt;/p&gt;

\[\alpha_{1 \times 7680} A_{7680\times 896}    = \beta_{ 1 \times 896}\]

&lt;p&gt;参数汇总：&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;1 window_infer = 8s&lt;/li&gt;
  &lt;li&gt;1 chunk/s&lt;/li&gt;
  &lt;li&gt;13 token/s&lt;/li&gt;
  &lt;li&gt;100 mel frame/s&lt;/li&gt;
  &lt;li&gt;token 向量的维数&lt;span style=&quot;color: red;&quot;&gt;$d_{model}$ &lt;/span&gt;= 896，重要&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;以上是音频相关的内容，token化得到 input embedding，接下来是LLM通用的步骤，也适用于图片、视频、文本token化之后的处理。&lt;/p&gt;

&lt;h2 id=&quot;22-transformer-21&quot;&gt;2.2 Transformer 21%&lt;/h2&gt;
&lt;div align=&quot;center&quot;&gt;
&lt;img src=&quot;../assets/pic/asr/transformer.png&quot; alt=&quot;transformer.png&quot; /&gt;
&lt;p&gt;Transformer架构&lt;/p&gt;
&lt;/div&gt;

&lt;h3 id=&quot;positional-encoding&quot;&gt;Positional Encoding&lt;/h3&gt;
&lt;p&gt;transformer如何利用输入序列中token的前后位置信息？引入Sinusoidal正弦曲线编码位置信息。[6][9]&lt;/p&gt;

&lt;div class=&quot;language-c highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;cm&quot;&gt;/* Add per-chunk sinusoidal position embeddings (starting from pos 0) */&lt;/span&gt;
&lt;span class=&quot;kt&quot;&gt;float&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pe&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;float&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;malloc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;w3&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sizeof&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;));&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;qwen_sinusoidal_pe&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pe&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;qwen_add_inplace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;projected&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pe&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w3&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;

&lt;span class=&quot;p&quot;&gt;...&lt;/span&gt;

&lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;qwen_sinusoidal_pe&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;float&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pe&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_pos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;half&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;kt&quot;&gt;float&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;log_timescale&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;half&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_pos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;++&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;kt&quot;&gt;float&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;row&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pe&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;half&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;++&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;kt&quot;&gt;float&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;inv_timescale&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;expf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;log_timescale&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
            &lt;span class=&quot;kt&quot;&gt;float&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;angle&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;inv_timescale&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;row&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sinf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;angle&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;          &lt;span class=&quot;cm&quot;&gt;/* first half: sin */&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;row&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;half&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cosf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;angle&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;   &lt;span class=&quot;cm&quot;&gt;/* second half: cos */&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;考察1s音频：&lt;/p&gt;

\[\begin{aligned}
 PE_{(p, d)} &amp;amp;= \sin(p*0.0001^{d/(d_{model}/2-1)}) \approx \sin(p * 0.9796^d) \\ 
PE_{(p, d_{model}/2+d)} &amp;amp;= \cos(p*0.0001^{d/(d_{model}/2-1)}) \approx \cos(p * 0.9796^d)
\end{aligned}\]

&lt;p&gt;前一半维度用sin，后一半用cos，称为 NeoX split-half 风格，使两个向量两两不同。&lt;/p&gt;

&lt;p&gt;&lt;em&gt;注：Attention论文中是偶数维用sin，奇数维用cos，类似于PCM的两种排列方式 interleaved 和 planar。与AI沟通，为什么使用split-half风格而不是奇偶交错呢？后面decode时有类似计算需要重用，对于SIMD友好，而encode阶段则无影响，这里可能是为了保持风格一致。&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;函数图像：&lt;/p&gt;

&lt;div align=&quot;center&quot;&gt;
&lt;img src=&quot;../assets/pic/asr/sin.png&quot; alt=&quot;sin.png&quot; /&gt;
&lt;p&gt;&lt;a href=&quot;https://echarts.apache.org/examples/en/editor.html?c=surface-wave&amp;amp;gl=1&amp;amp;code=fVTNctowEL7zFDvTA5BJggwGipkeOumhl_TQayf1CCQbNUZyZTmYZPIMeZzO9H3yHl1J_sEtDQc8--3q2x992jSu4r2Q8AHIeuAMWqERTNcDNI-nPjScLwyXzplrzsTWxI910FWwhskEEqVhqzKl-yGeFg9Wca6ENLEs9xuuLUiQ_ngWreLC8BytUVPaFdQVj2ECfSpL0oX7am24a8KG93OcsJNrLKw9bFtXuRHKNvU0ADBKZUbkETw9X6K5odv7VKtSshvbZgTDd0mSDK3rQRQlzW6pjUUT7DyKnTpEkNCs4DYEgIk9lwXSRzD1CNYXYaG9gdYeWv3loZX3CPmVypQ3icDPPIJvtQlY1iyYLVZzV1kDhfPlfBP2oGVIGQt6EN2wFV_1IE6SWfK-B2HXycY33kKckxXpQ4zyRZ8-CRcsnPUgtpyR6bJfxJyQ6WJYI3fu-4z_7hKqj5UoZp-a9iXd4yiGRt1zCa-_X15ffkEOI4J3h1oe17zmmNuoB5qV3PI6puNZJlYfZvFeMZ5NplfBmyyPZ1kKIUf5BbkmhATfR2wyOqUb_4_QycbdfOAD0IQiz4T54pSLumnSplqwLuuD4IcbJY1WWacLPJxr9YNvraIxjdJmp1JN853Y-mx2qD7JRlWfuUh3JoKQ-Bz4X3AteNFIq-Gtqy5KndAtb2_uIDRPtGu_iawb6N5BjbsOGjf-ih1lQqZI6rTcUvKfJfXFd4w4nM5oX5DbDJ2G2vfjdscpbp96hPvDflu4rQdFcZbebZIz9G7X_EvvN8o5-kccRCndjcCouoTjuJdOc1NqCbfU7K6thCq48EauDiOvJjyDGw1X8Xi87jI0g22v9W7wvP4D&amp;amp;enc=deflate&quot; target=&quot;_blank&quot;&gt;sin PE&lt;/a&gt;&lt;/p&gt;
&lt;/div&gt;

&lt;div align=&quot;center&quot;&gt;
&lt;img src=&quot;../assets/pic/asr/cos.png&quot; alt=&quot;cos.png&quot; /&gt;
&lt;p&gt;&lt;a href=&quot;https://echarts.apache.org/examples/en/editor.html?c=surface-wave&amp;amp;gl=1&amp;amp;code=fVRLbtswEN37FAN0YTlIYsqW7VpGF0W66CZddFukAi1SMhtZVCkqlhPkDDlOgd4n9-iQ1Mdq3XhhYd4M33z4OGlUR3uRwwcgm5E1aI2GP9uM0Dye-tCwviBYWWehOBOxjh6boCt_A9MpJFJBLDOphiGOFg_WUSFFrqO82m-5MiBB-uNZtI5KzQu0vLa0K2gqnsAUhlSGpA931Zpw24QJH-Y4YSfXWFh32LQuCy2kaeppBKClzLQoQnh6vkRzS-P7VMkqZzemzRDG75IkGRvXgygrmt1SE4smmHmUO3kIIaFZyU0IABN7npdIH8LMIVhfiIUOBtp4aP2Xh9bOI_KvNE95mwjczEP41piAZc39-XK9sJW1ULBYLbbBAFoFlDF_ANEtW_P1AOIkmSfvBxB2nWxd4x3EOVmTIcQoXw7pk2DJgvkAYqs5ma2GRSwImS3HDXJnv8_4by-h_liLcv6pbT-nexzFWMt7nsPr75fXl19QgEfw7lDLk4ZXHwsT9UCzihtey3Q8y8SawyzaS8az6ezKf5Pl8SxLLEuvuCDXhBD_u8em3ind5H-EVjb25n0XgCaURSb0F6tc1E2bNlWC9VkfBD_cyFwrmfW6wMOFkj94bBSNaaTSO5kqWuxE7LKZobokW1l_5iLd6RAC4nLgf8mV4GUrrZa3qbqsVEJj3t3cQSieKNt-G9k00L-DBrcdtG78lTvKRJ7auaGWO0r-s6Ku-J4Rh9Mb3Quym6HXUPd-7O44xc1TD3F_mG8Hd_WgKM7S201yht7umn_p3UY5R_-Ig6hyeyPg1ZdwnAzSKa4rlcMt1btrI6EaLpxRyIPn1IRncKPhKp5MNn2GdrDdtd6Nnjd_AA&amp;amp;enc=deflate&quot; target=&quot;_blank&quot;&gt;cos PE&lt;/a&gt;&lt;/p&gt;
&lt;/div&gt;

&lt;p&gt;注意到d越大，三角函数的频率越低，最后将PE向量与token向量相加，得到最终的embedding。&lt;/p&gt;

&lt;h3 id=&quot;attention-7&quot;&gt;Attention 7%&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Pre-attention LayerNorm&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;数据处理技巧，将一个token向量标准化为均值0、方差1，避免数值间相差太大，w、b向量训练时得到，突出和抑制某些维度。&lt;/p&gt;

\[\text{LayerNorm}(x) = \frac{x-\mu}{\sigma} \odot w + b\]

&lt;p&gt;&lt;em&gt;注：规范名称应是 Standardization（标准化） 或者 z-score，不是 Normalization (归一化，有 L1, L2, min-max, RMS 等) [2] ; $\odot$ 表示逐元素相乘，即 Hadamard 积&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;token预处理成Query/Key/Value向量&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;为降低理解门槛，考察单个token向量 x ，通过三个训练时得到的weight矩阵 $W_q$, $W_k$, $W_v$和三个bias向量（有的模型没有），分别得到 q, k, v 三个向量。&lt;/p&gt;

\[\begin{aligned}
q &amp;amp;= x W_q + b_q \\
k &amp;amp;= x W_k + b_k \\
v &amp;amp;= x W_v + b_v
\end{aligned}\]

&lt;ul&gt;
  &lt;li&gt;$W_q$: 训练过程中，$W_q$ 会学习到输入中适合作为 “查询” 的特征：
比如x是代词 “它”，$W_q$ 会让 q 聚焦于 “查询前文指代的名词”；
比如x是动词，q 会聚焦于 “查询主语 / 宾语”。&lt;/li&gt;
  &lt;li&gt;$W_k$: 给 token 打 “可被检索的标签”，表示”我包含什么”，提供给q查询。&lt;/li&gt;
  &lt;li&gt;$W_v$: 掏出 token 的 “干货内容”，q、k匹配成功后，真正传给其他 token 的就是它。&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;打个比方，新生入学班上的同学们作自我介绍，大家都很好奇对方，比如你可能对某位女同学的长相感兴趣，你会多关注到她一些，介绍完后你就想了解她的详细情况，比如她的家庭住址、生日、爱好等等。&lt;/p&gt;

&lt;p&gt;在这个例子中，我们看到几个重要过程:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;第一个你的需求query，你关注长相，有的人关注性格，有的关注别人的学习成绩等等&lt;/li&gt;
  &lt;li&gt;第二个是其他同学的特征或者说标签，称为key，比如她有什么优点、特长？&lt;/li&gt;
  &lt;li&gt;第三个是同学的详细信息，称为value&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;你的需求和她的特点匹配上了，然后了解她的详情，就是这个过程。&lt;/p&gt;

&lt;p&gt;再看下假如没有这个自我介绍会怎么样？大家坐一起干巴巴地，就在尬聊，互相认识的效果不太好。而这个自我介绍过程相当于对token作预处理，提取出token的query、key、value。&lt;/p&gt;

&lt;p&gt;Without these projections, attention would just compare raw embeddings directly. The learned projections allow the model to learn what aspects of the input to compare (keys vs. queries) and what information to pass forward (values).&lt;/p&gt;

&lt;p&gt;再举一个例子，以句子 “猫在睡觉，它很可爱” 为例：&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;x=”它”，$W_q$ → q：我要查【前文被指代的名词】&lt;/li&gt;
  &lt;li&gt;x=”猫”，$W_k$ → k：我是【可被指代的实体名词】→ 匹配成功，高分(后面将介绍计算方法)&lt;/li&gt;
  &lt;li&gt;v：匹配到猫之后，携带【猫的所有实际语义：动物、在睡觉】&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;前面例子中把需求和标签配对，获取详情的过程，怎么用代码或者公式精确表达？下面就是transformer架构最核心的部分。&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Attention&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;多个token预处理后写成矩阵形式 Q, K, V，每一行表示一个token预处理后的结果，经典的Attention公式如下 [3][8]。&lt;/p&gt;

\[\text{Attention}(Q, K, V) = \text{softmax}\left(\frac{QK^T}{\sqrt{d}}\right)V\]

&lt;p&gt;$QK^T$的含义是两两token（包括自己和自己）的q向量与k向量求内积$\langle q, k \rangle=qk^T$，表示&lt;span style=&quot;color: red;&quot;&gt;相似度&lt;/span&gt;。比如有3个token:&lt;/p&gt;

\[QK^T
=\begin{pmatrix}
 q_1   \\
 q_2 \\
q_3  
\end{pmatrix} \begin{pmatrix}
 k_1   \\
 k_2 \\
k_3 
\end{pmatrix}^T
=\begin{pmatrix}
 q_1   \\
 q_2 \\
q_3  
\end{pmatrix} \begin{pmatrix}
 k_1^T &amp;amp; k_2^T  &amp;amp;k_3^T 
\end{pmatrix} 
= \begin{pmatrix}
\langle q_1, k_1 \rangle &amp;amp; \langle q_1, k_2 \rangle &amp;amp; \langle q_1, k_3 \rangle \\
\langle q_2, k_1 \rangle &amp;amp; \langle q_2, k_2 \rangle &amp;amp; \langle q_2, k_3 \rangle \\
\langle q_3, k_1 \rangle &amp;amp; \langle q_3, k_2 \rangle &amp;amp; \langle q_3, k_3 \rangle 
\end{pmatrix}\]

&lt;p&gt;除以$\sqrt{d}$ 和 softmax 可认为是一种数据处理技巧，避免数值间相差太大。假设q、k向量的元素是独立随机变量，由前面的LayerNorm得知$\langle q, k \rangle$标准差是$\sqrt{d}$，除以它使标准化；softmax分别对矩阵的每一行处理，得到&lt;span style=&quot;color: red;&quot;&gt;概率分布列&lt;/span&gt;，下面用$\langle q, k \rangle’$表示，与V加权求和得到数学期望。实现中使用更高效的online softmax。&lt;/p&gt;

\[\begin{pmatrix}
\langle q_1, k_1 \rangle&apos; &amp;amp; \langle q_1, k_2 \rangle&apos; &amp;amp; \langle q_1, k_3 \rangle&apos; \\
\langle q_2, k_1 \rangle&apos; &amp;amp; \langle q_2, k_2 \rangle&apos; &amp;amp; \langle q_2, k_3 \rangle&apos; \\
\langle q_3, k_1 \rangle&apos; &amp;amp; \langle q_3, k_2 \rangle&apos; &amp;amp; \langle q_3, k_3 \rangle&apos; 
\end{pmatrix}  \begin{pmatrix}
 v_1   \\
 v_2 \\
v_3 
\end{pmatrix}
=\begin{pmatrix}
\sum \langle q_1, k_i \rangle&apos; v_i   \\
\sum \langle q_2, k_i \rangle&apos; v_i   \\
\sum \langle q_3, k_i \rangle&apos; v_i
\end{pmatrix}\]

&lt;p&gt;例如考查token 1与所有token的attention:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;原始相似度&lt;/th&gt;
      &lt;th&gt;$ \langle q_1, k_1 \rangle $&lt;/th&gt;
      &lt;th&gt;$ \langle q_1, k_2 \rangle $&lt;/th&gt;
      &lt;th&gt;$ \langle q_1, k_3 \rangle $&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;经缩放和softmax&lt;/td&gt;
      &lt;td&gt;$\langle q_1, k_1 \rangle’ $&lt;/td&gt;
      &lt;td&gt;$ \langle q_1, k_2 \rangle’ $&lt;/td&gt;
      &lt;td&gt;$ \langle q_1, k_3 \rangle’ $&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;示例值&lt;/td&gt;
      &lt;td&gt;11%&lt;/td&gt;
      &lt;td&gt;2%&lt;/td&gt;
      &lt;td&gt;87%&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;概率分布列：&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;value&lt;/th&gt;
      &lt;th&gt;$v_1$&lt;/th&gt;
      &lt;th&gt;$v_2$&lt;/th&gt;
      &lt;th&gt;$v_3$&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;概率&lt;/td&gt;
      &lt;td&gt;11%&lt;/td&gt;
      &lt;td&gt;2%&lt;/td&gt;
      &lt;td&gt;87%&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;结果为数学期望 a=11%$v_1$ + 2%$v_2$ + 87%$v_3$&lt;/p&gt;

&lt;p&gt;Multi-Head Attention&lt;/p&gt;

&lt;p&gt;将$d_{model}$平均分成 h 份，每份维度$d_{k}$（Qwen3ASR 0.6B将896维划分为14份，每份64维）。每份就是head的意思。每份独立计算Attention，向量维度$d_{k}$，所有份完成后拼接回向量a，维度 $d_{model}$，最后线性变换a整合各份结果：&lt;/p&gt;

&lt;p&gt;x += $a W_o + b_o$&lt;/p&gt;

&lt;div align=&quot;center&quot;&gt;
&lt;img src=&quot;../assets/pic/asr/multihead-attention.drawio.png&quot; alt=&quot;attention&quot; /&gt;
&lt;p&gt;分head，分window处理，虚线表示token&lt;/p&gt;
&lt;/div&gt;

&lt;h3 id=&quot;feed-forward-network-ffn-14&quot;&gt;Feed-Forward Network (FFN) 14%&lt;/h3&gt;
&lt;p&gt;逐token独立处理，不涉及跨token处理。
首先 Pre-FFN LayerNorm，类似 Pre-Attention LayerNorm，只是w、b向量不同。&lt;/p&gt;

\[\text{FFN}(x)=\text{GeLU}(xW_1+b_1)W_2+b_2\]

&lt;p&gt;After attention gathers context, FFN processes it through a wider hidden layer:&lt;br /&gt;
x [166, 896]  →  fc1 [896, 3584]  →  GeLU  →  fc2 [3584, 896]  →  x [166, 896]&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;896 → 3584: “expand and look at the data from 3584 different angles”, 升维4倍&lt;/li&gt;
  &lt;li&gt;GeLU:       “keep useful signals, suppress noise”&lt;/li&gt;
  &lt;li&gt;3584 → 896: “compress back to original size with new understanding”&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;最后 x += FFN(x)&lt;/p&gt;
&lt;h3 id=&quot;n层循环&quot;&gt;N层循环&lt;/h3&gt;

&lt;p&gt;How 18 Layers Build Understanding&lt;/p&gt;

&lt;p&gt;Each layer adds more abstraction:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Layer  1-3:  Low-level: detect phonemes, formants, pitch changes&lt;/li&gt;
  &lt;li&gt;Layer  4-8:  Mid-level: recognize syllables, word boundaries&lt;/li&gt;
  &lt;li&gt;Layer  9-14: High-level: understand words, short phrases&lt;/li&gt;
  &lt;li&gt;Layer 15-18: Contextual: resolve ambiguity using surrounding context&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Example for “今天天气不错” (nice weather today):&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;After layer 3:  tokens know: [jin] [tian] [tian] [qi] [bu] [cuo]&lt;/li&gt;
  &lt;li&gt;After layer 10: tokens know: [jintian] [tianqi] [bucuo]&lt;/li&gt;
  &lt;li&gt;After layer 18: tokens know: [今天] [天气] [不错] with full context&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;adapt-dimension-for-decoder&quot;&gt;Adapt dimension for decoder&lt;/h3&gt;
&lt;p&gt;Final projection目的是为了适配decoder的维度，从896维到1024维:&lt;/p&gt;

\[\text{GeLU}(xW_1+b_1)W_2+b_2\]

&lt;p&gt;&lt;em&gt;注：W, b与FFN的不同&lt;/em&gt;&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt; &lt;/th&gt;
      &lt;th&gt;FFN (×18)&lt;/th&gt;
      &lt;th&gt;Final Projection (×1)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Expands?&lt;/td&gt;
      &lt;td&gt;Yes: 896 → 3584 → 896 (4× wider)&lt;/td&gt;
      &lt;td&gt;No: 896 → 896 → 1024&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Returns to same dim?&lt;/td&gt;
      &lt;td&gt;Yes: 896 → 896&lt;/td&gt;
      &lt;td&gt;No: 896 → 1024 (new size!)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Has residual?&lt;/td&gt;
      &lt;td&gt;Yes: x = x + ffn_out&lt;/td&gt;
      &lt;td&gt;No residual&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Purpose&lt;/td&gt;
      &lt;td&gt;Learn nonlinear transformations&lt;/td&gt;
      &lt;td&gt;Change dimension for decoder&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Repeated?&lt;/td&gt;
      &lt;td&gt;18 times&lt;/td&gt;
      &lt;td&gt;Once, at the very end&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;h1 id=&quot;3-准备-prompt&quot;&gt;3. 准备 Prompt&lt;/h1&gt;
&lt;p&gt;Building the decoder’s input by combining text token embeddings with encoder audio embeddings into one flat array. The decoder expects input in a chat format. This code builds it as an embedding array input_embeds [total_seq, 1024]:&lt;/p&gt;

&lt;p&gt;Token IDs:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Token IDs&lt;/th&gt;
      &lt;th&gt;Section&lt;/th&gt;
      &lt;th&gt;Token Count&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[&amp;lt;im_start&amp;gt;] [system] [\n]&lt;/code&gt;&lt;/td&gt;
      &lt;td&gt;prefix head&lt;/td&gt;
      &lt;td&gt;3 tokens&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[optional system prompt tokens...]&lt;/code&gt;&lt;/td&gt;
      &lt;td&gt;user prompt&lt;/td&gt;
      &lt;td&gt;0 tokens default&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[&amp;lt;im_end&amp;gt;] [\n] [&amp;lt;im_start&amp;gt;] [user] [\n] [&amp;lt;audio_start&amp;gt;]&lt;/code&gt;&lt;/td&gt;
      &lt;td&gt;prefix tail&lt;/td&gt;
      &lt;td&gt;6 tokens&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[ENCODER_OUTPUT_0] [ENCODER_OUTPUT_1] ... [ENCODER_165]&lt;/code&gt;&lt;/td&gt;
      &lt;td&gt;audio&lt;/td&gt;
      &lt;td&gt;166 tokens&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[&amp;lt;audio_end&amp;gt;] [&amp;lt;im_end&amp;gt;] [\n] [&amp;lt;im_start&amp;gt;] [assistant] [\n]&lt;/code&gt;&lt;/td&gt;
      &lt;td&gt;suffix&lt;/td&gt;
      &lt;td&gt;6 tokens&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Total: 3 + 0 + 6 + 166 + 6 = 181 tokens&lt;/p&gt;

&lt;h1 id=&quot;4-prefill-42&quot;&gt;4. Prefill 42%&lt;/h1&gt;
&lt;div class=&quot;language-c highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;// 输入180个token，保留最后一个token用于decode阶段解码产生结果&lt;/span&gt;
&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;prefill_len&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;total_seq&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;cm&quot;&gt;/* prefill all but last */&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;qwen_decoder_prefill&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ctx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_embeds&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;prefill_len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;source: &lt;a href=&quot;https://sourcegraph.com/r/github.com/antirez/qwen-asr@b00b789b17051aea61e9717458171100662318a4/-/blob/qwen_asr.c?L706&quot; target=&quot;_blank&quot;&gt;https://sourcegraph.com/r/github.com/antirez/qwen-asr@b00b789b17051aea61e9717458171100662318a4/-/blob/qwen_asr.c?L706&lt;/a&gt;&lt;/p&gt;

&lt;h3 id=&quot;rope&quot;&gt;RoPE&lt;/h3&gt;
&lt;p&gt;旋转位置编码 Rotary Position Embedding [7], 按原论文习惯q, k用列向量，经位置编码后计算两者的相似度：&lt;/p&gt;

\[\langle R(x)q, R(y)k\rangle = (R(x)q)^TR(y)k = q^TR(x)^TR(y)k=q^TR(x)^{-1}R(y)k = q^TR(y-x)k\]

&lt;p&gt;其中旋转矩阵R是正交矩阵，转置等于逆，逆表示向相反方向旋转，可以看到&lt;span style=&quot;color: red;&quot;&gt;结果中只与两个token的相对位置y-x有关&lt;/span&gt;。向量维数是2时旋转矩阵如下（可以推广到更多维向量，见原论文）&lt;/p&gt;

\[R(x)= \begin{pmatrix} \cos x &amp;amp; -\sin x \\ \sin x &amp;amp; \cos x \end{pmatrix}\]

\[x=p*0.000001^{d/(head\_dim/2)} \approx p * 0.8058^d\]

&lt;p&gt;&lt;em&gt;注：RoPE论文中使用的底数是$10^{-4}$，Qwen3ASR代码中使用的是$10^{-6}$&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;计算好R的元素存储，便于后续计算复用。&lt;/p&gt;

&lt;p&gt;另外一种推导相似度只与相对位置有关的方法是使用复数，与旋转矩阵的方法等价，向量维数是2时，它与一个复数一一对应，第一个分量对应复数的实部，第二个分量对应复数的虚部，把q, k看成复数，那么相似度计算变成&lt;/p&gt;

\[\langle e^{ix}q, e^{iy}k\rangle
= \text{Re}[\overline{e^{ix}q} e^{iy}k]
= \text{Re}[e^{-ix}\overline{q} e^{iy}k]
= \text{Re}[\overline{q}e^{i(y-x)}k]\]

&lt;p&gt;可以看到结果也只与y-x有关，实际计算还是用矩阵的方式方便。&lt;/p&gt;

&lt;p&gt;对比矩阵与复数两种方法：&lt;/p&gt;

\[R(x)q= \begin{pmatrix} \cos x &amp;amp; -\sin x \\ \sin x &amp;amp; \cos x \end{pmatrix} \begin{pmatrix} x_1 \\ x_2 \end{pmatrix} = \begin{pmatrix} x_1 \cos x  - x_2 \sin x \\ x_1 \sin x +x_2 \cos x \end{pmatrix}\]

\[e^{ix}q=(\cos x +i \sin x) (x_1 + i x_2)=x_1\cos x - x_2 \sin x +(x_1 \sin x + x_2 \cos x)i\]

&lt;h3 id=&quot;attention&quot;&gt;Attention&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Pre-attention RMSNorm&lt;/strong&gt;&lt;/p&gt;

\[\text{RMSNorm}(x) = \frac{x}{\text{RMS}(x)} \odot w\]

&lt;p&gt;$\frac{x}{\text{RMS}(x)}$ 的模固定是$\sqrt{n}=\sqrt{1024}=32$，向量的方向保持，大小归一化&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;token预处理成Query/Key/Value向量&lt;/strong&gt;&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;特性&lt;/th&gt;
      &lt;th&gt;MHA (Multi-head attention)&lt;/th&gt;
      &lt;th&gt;GQA (Grouped-query attention)[10]&lt;/th&gt;
      &lt;th&gt;MQA (Multi-query attention)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Q&lt;/td&gt;
      &lt;td&gt;H 个独立&lt;/td&gt;
      &lt;td&gt;H 个独立&lt;/td&gt;
      &lt;td&gt;H 个独立&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;K, V&lt;/td&gt;
      &lt;td&gt;H 个独立&lt;/td&gt;
      &lt;td&gt;G 个独立 (G&amp;lt;H)&lt;/td&gt;
      &lt;td&gt;1 个共享&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;KV 缓存大小&lt;/td&gt;
      &lt;td&gt;O(H·L·d)&lt;/td&gt;
      &lt;td&gt;O(G·L·d)&lt;/td&gt;
      &lt;td&gt;O(1·L·d)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;性能&lt;/td&gt;
      &lt;td&gt;最高&lt;/td&gt;
      &lt;td&gt;接近 MHA&lt;/td&gt;
      &lt;td&gt;最低&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;推理速度&lt;/td&gt;
      &lt;td&gt;最慢&lt;/td&gt;
      &lt;td&gt;中等&lt;/td&gt;
      &lt;td&gt;最快&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;通俗理解&lt;/td&gt;
      &lt;td&gt;每个研究员都带一套完整参考书 → 知识全面但成本高&lt;/td&gt;
      &lt;td&gt;几位研究员组成小组，每组共用一套参考书 → 成本适中且知识覆盖足够&lt;/td&gt;
      &lt;td&gt;所有研究员共用一套参考书 → 成本低但可能不够用&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;使用折中方案 GQA&lt;/p&gt;

&lt;p&gt;参数汇总：&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;H=16个head&lt;/li&gt;
  &lt;li&gt;G=8个组（每组2个head）&lt;/li&gt;
  &lt;li&gt;L=输入token数目180个&lt;/li&gt;
  &lt;li&gt;d=head_dim 每个head 128维&lt;/li&gt;
  &lt;li&gt;hidden=decoder token的维数1024维&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Per-head Q, K RMSNorm&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;对每个token计算 $R(m\theta)q$, $R(n\theta)k$&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;此时将复用之前计算好的sin, cos值，可使用SIMD加速。&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;span style=&quot;color: red;&quot;&gt;存储$RK$和$V$到缓存&lt;/span&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;div class=&quot;language-c highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;        &lt;span class=&quot;cm&quot;&gt;/* Apply NeoX RoPE */&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;qwen_apply_rope_neox&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rope_cos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rope_sin&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seq_len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_heads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;head_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;qwen_apply_rope_neox&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rope_cos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rope_sin&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seq_len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_kv_heads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;head_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;

        &lt;span class=&quot;cm&quot;&gt;/* Store K, V in cache */&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seq_len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;++&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;memcpy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;kv_cache_k_at&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ctx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;start_pos&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
                   &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kv_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kv_dim&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;sizeof&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;));&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;memcpy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;kv_cache_v_at&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ctx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;start_pos&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
                   &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kv_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kv_dim&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;sizeof&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;));&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

        &lt;span class=&quot;cm&quot;&gt;/* Causal attention */&lt;/span&gt;
        &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;total_seq&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;start_pos&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seq_len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
        &lt;span class=&quot;kt&quot;&gt;float&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;full_k&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kv_cache_k_at&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ctx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
        &lt;span class=&quot;kt&quot;&gt;float&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;full_v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kv_cache_v_at&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ctx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;qwen_causal_attention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;attn_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;full_k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;full_v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                               &lt;span class=&quot;n&quot;&gt;seq_len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;total_seq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_heads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_kv_heads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                               &lt;span class=&quot;n&quot;&gt;head_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;start_pos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;source: &lt;a href=&quot;https://sourcegraph.com/r/github.com/antirez/qwen-asr@main/-/blob/qwen_asr_decoder.c?L319&quot; target=&quot;_blank&quot;&gt;https://sourcegraph.com/r/github.com/antirez/qwen-asr@main/-/blob/qwen_asr_decoder.c?L319&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;计算注意力分数&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Q [180 new queries, 16 heads, 128 dims]&lt;/li&gt;
  &lt;li&gt;K [180 cached keys,   8 heads, 128 dims]  (from KV cache)&lt;/li&gt;
  &lt;li&gt;V [180 cached values,  8 heads, 128 dims]&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;span style=&quot;color: red;&quot;&gt;Causal mask&lt;/span&gt; — token i only attends to positions ≤ i: &lt;br /&gt;
Q at pos 0:   attends to K at [0] &lt;br /&gt;
Q at pos 5:   attends to K at [0,1,2,3,4,5] &lt;br /&gt;
Q at pos 179: attends to K at [0,1,…,179]&lt;/p&gt;

&lt;p&gt;GQA — &lt;span style=&quot;color: red;&quot;&gt;every 2 Q heads share 1 KV head&lt;/span&gt;: &lt;br /&gt;
Q heads 0,1   use K/V head 0 &lt;br /&gt;
Q heads 2,3   use K/V head 1 &lt;br /&gt;
… &lt;br /&gt;
Q heads 14,15 use K/V head 7&lt;/p&gt;

&lt;p&gt;Output: attn_out [180, 2048] (16 heads × 128 dims)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;输出attention&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;x += $a W_o$&lt;br /&gt;
a 维度1$\times$2048, $W_o$ 维度 2048$\times$1024&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Post-attention RMSNorm&lt;/strong&gt;&lt;/p&gt;

&lt;h3 id=&quot;feed-forward-network-ffn&quot;&gt;Feed-Forward Network (FFN)&lt;/h3&gt;
&lt;p&gt;\(\text{FFN}(x)=\text{SwiGLU}(x_{1\times 1024}W_{1024\times 6144})W_{3072\times 1024}\)&lt;/p&gt;

&lt;p&gt;SwiGLU:&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;gate_val = gate_up[2*i]       // even positions = gate
up_val   = gate_up[2*i + 1]   // odd positions = up (content)
gate[i] = SiLU(gate_val) × up_val
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;最后 x += FFN(x)&lt;/p&gt;

&lt;div align=&quot;center&quot;&gt;
&lt;img src=&quot;../assets/pic/asr/activation.png&quot; alt=&quot;activation.png&quot; width=&quot;800&quot; /&gt;
&lt;p&gt;&lt;a href=&quot;https://echarts.apache.org/examples/en/editor.html?c=surface-wave&amp;amp;gl=1&amp;amp;code=3VRNb9pAEL3zK0aKKq8TQk0AhZpSqarUqlIqVUU9IRQtsOCVzK5rL806Ff-9M95dvk6tkkvCwXjem9l5fjP2-t7eb6SCMVwPRq0m4hYjDDCqA9clDqM9pwsjNVF_WgALnesyhWl0IQa9d71B1IbooiuGQ-Fu-z2e9G-jWRtzc7EWapk2dQBLbjgV_hB3Pyl1It3_F4qbfKpYmRSihVBGlJHD5toYvUmhm7hYlxJpzMrw7lErw3OfaYQ1E1PnIrQEWCH_mW9kXmPBJ60qnfPKpzt2Ih8x_yZpoB1ed8QarXMjCzwITCnXa4HPHHErq8jx61LuH8yL7r3x52J-RkA_AOEJomFAFiRbqjs-F3mKHbYiNLYfsUk42dQFaot-83wrfCUOKQU_SY9w6xFuHSLJPSxCzxxAwn2vpxpT_5u-ZptO9DUb9exyKoHbgHqmDRxOU3xDutymecxrzaUKUrG63sw1qoiUPkIpJawRPMilybCva3fYY8ZiGH_Yd6QtMFCKCl-T6Wy0R1e6BEYUvUx-bCMM3vuIW4quxpB0kkF8dByukag6xbbK2NS24Rs3WQezWdIGG8_iQweyIhSYbamoLrC7mMXOLyf-zB_3Br4Kfyy8BdaFK2eUsAW7tvFz-dR8oV6sT1RVw_gIAcwawOUJYs9iMvMEAGet4SpjZ4Snql-lYTc4iCb6_jWGS2AoijT1-7ddbOmoQj8wnFkvdqYffvHRvM4GXP__LPE6a-1GfwE&amp;amp;enc=deflate&quot; target=&quot;_blank&quot;&gt;激活函数比较&lt;/a&gt;&lt;/p&gt;
&lt;/div&gt;

&lt;h3 id=&quot;n层循环-1&quot;&gt;N层循环&lt;/h3&gt;
&lt;p&gt;28 layers, 每层参数不同&lt;/p&gt;

&lt;h1 id=&quot;5-decode-13&quot;&gt;5. Decode 13%&lt;/h1&gt;
&lt;p&gt;首先输入prefill时遗留的最后一个token，decode返回一个token。&lt;/p&gt;
&lt;div class=&quot;language-c highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;cm&quot;&gt;/* First token from last prefill position */&lt;/span&gt;
&lt;span class=&quot;kt&quot;&gt;float&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;last_embed&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_embeds&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;size_t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;prefill_len&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;token&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;qwen_decoder_forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ctx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;last_embed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;free&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_embeds&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;source: &lt;a href=&quot;https://sourcegraph.com/r/github.com/antirez/qwen-asr@b00b789b17051aea61e9717458171100662318a4/-/blob/qwen_asr.c?L710&quot; target=&quot;_blank&quot;&gt;https://sourcegraph.com/r/github.com/antirez/qwen-asr@b00b789b17051aea61e9717458171100662318a4/-/blob/qwen_asr.c?L710&lt;/a&gt;&lt;/p&gt;

&lt;h3 id=&quot;attention-1&quot;&gt;Attention&lt;/h3&gt;
&lt;p&gt;处理单个token，流程与之前类似。&lt;br /&gt;
存储本token的kv到kv cache中。计算与之前token的attention，即 causal attention。&lt;/p&gt;

&lt;h3 id=&quot;ffn&quot;&gt;FFN&lt;/h3&gt;
&lt;p&gt;处理单个token，流程与之前类似。&lt;/p&gt;
&lt;h3 id=&quot;n层循环-2&quot;&gt;N层循环&lt;/h3&gt;
&lt;p&gt;处理单个token，流程与之前类似。&lt;/p&gt;

&lt;h3 id=&quot;输出一个token&quot;&gt;输出一个token&lt;/h3&gt;
&lt;p&gt;最后做一次RMSNorm，与词表（共151936条）中的每个向量（1024维）做点积比较，最大值的词即结果。&lt;/p&gt;

&lt;div class=&quot;language-c highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;cm&quot;&gt;/* Final norm + streaming argmax (no logits buffer needed) */&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;qwen_rms_norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dec&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;eps&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;qwen_argmax_matvec_bf16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dec&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tok_embeddings_bf16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cfg&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vocab_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;识别到结束，即解码出 QWEN_TOKEN_ENDOFTEXT 或 QWEN_TOKEN_IM_END token，或者达到输出token数目上限结束。&lt;/p&gt;

&lt;h1 id=&quot;后记&quot;&gt;后记&lt;/h1&gt;

&lt;p&gt;以上就是 LLM ASR 的识别过程，这里只讲了CPU上运行的基本流程，运行在GPU上的优化手段也值得讨论 [4]。回顾 2017 年 Transformer 架构推出后，RoPE、在线 Softmax、SwiGLU、GQA 等优化技术相继涌现，有的为了降成本，有的为了提升效果，很多是围绕着大矩阵乘法$QK^T$这个公式的优化，行业研究者不断迭代、丰富架构细节，共同搭建出当下主流的大模型框架。&lt;/p&gt;

&lt;p&gt;参考资料：&lt;/p&gt;

&lt;p&gt;[1] qwen-asr C语言版 &lt;a href=&quot;https://github.com/antirez/qwen-asr&quot; target=&quot;_blank&quot;&gt;https://github.com/antirez/qwen-asr&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;[2] Normalization v.s. Standardization &lt;a href=&quot;https://stats.stackexchange.com/a/10298&quot; target=&quot;_blank&quot;&gt;https://stats.stackexchange.com/a/10298&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;[3] Attention Is All You Need &lt;a href=&quot;https://arxiv.org/abs/1706.03762&quot; target=&quot;_blank&quot;&gt;https://arxiv.org/abs/1706.03762&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;[4] vLLM 推理加速 &lt;a href=&quot;https://km.woa.com/articles/show/659449&quot; target=&quot;_blank&quot;&gt;https://km.woa.com/articles/show/659449&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;[5] CNN kernel 通俗解释 &lt;a href=&quot;https://www.bilibili.com/video/BV1dbokBXEiv&quot; target=&quot;_blank&quot;&gt;https://www.bilibili.com/video/BV1dbokBXEiv&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;[6] 苏剑林 Sinusoidal位置编码追根溯源 &lt;a href=&quot;https://kexue.fm/archives/8231&quot; target=&quot;_blank&quot;&gt;https://kexue.fm/archives/8231&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;[7] 苏剑林等 RoPE位置编码 &lt;a href=&quot;https://arxiv.org/abs/2104.09864&quot; target=&quot;_blank&quot;&gt;https://arxiv.org/abs/2104.09864&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;[8] 苏剑林 Attention论文解读 &lt;a href=&quot;https://kexue.fm/archives/4765&quot; target=&quot;_blank&quot;&gt;https://kexue.fm/archives/4765&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;[9] 苏剑林 Transformer位置编码 &lt;a href=&quot;https://kexue.fm/archives/8130/comment-page-7#comment-29329&quot; target=&quot;_blank&quot;&gt;https://kexue.fm/archives/8130/comment-page-7#comment-29329&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;[10] GQA (Grouped-query attention) &lt;a href=&quot;https://arxiv.org/abs/2305.13245&quot; target=&quot;_blank&quot;&gt;https://arxiv.org/abs/2305.13245&lt;/a&gt;&lt;/p&gt;
</description>
        <pubDate>Thu, 16 Apr 2026 00:00:00 +0000</pubDate>
        <link>https://justme0.com//archive/asr.html</link>
        <guid isPermaLink="true">https://justme0.com//archive/asr.html</guid>
        
        
      </item>
    
      <item>
        <title>机器学习模型评价指标整理</title>
        <description>&lt;style&gt;
  img {
    display: block;
    margin: 0 auto;
  }
&lt;/style&gt;

&lt;p&gt;如何量化机器学习的模型性能？本文整理了机器学习模型性能度量指标，主要是我对这些指标的一些思考。这里说的“性能”指模型泛化（即预测）能力 performance，不是指在机器上运行消耗资源的多少。&lt;/p&gt;

&lt;h1 id=&quot;1-recall--precision&quot;&gt;1. recall &amp;amp; precision&lt;/h1&gt;

&lt;p&gt;最常见的指标有recall（召回率，查全率），precision（查准率）。“召回”一词来自制造业，比如某款汽车售卖到市场上后发现有安全问题需要回收，关心有没有把所有有问题的汽车都找到回收了，以及有没有误回收[1]。&lt;/p&gt;

&lt;p&gt;另外还有准确率、精确率的叫法，各个地方翻译得不一样，中文的“博大精深”，在这里增加了不必要的麻烦，比如accuracy网络上大多称准确率，周志华《机器学习》书中称为“精度”，而网络上是将precision称为精确率。精确率、准确率本身也不够见名知义，本文将用英文单词叙述。我读研时是做程序静态分析的，用工具查找程序缺陷，在这个领域用的指标是漏报率（false negative rate）和误报率（false discovery rate，注意不叫 false positive rate），漏报率就是1-recall，误报率是1-precision，这两个名称能够见名知义。&lt;/p&gt;

&lt;p&gt;维基百科上这张图总结得很全[2]，红框中是常用的指标。&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;../assets/pic/ml/wiki.png&quot; alt=&quot;image.png&quot; /&gt;&lt;/p&gt;

&lt;!-- more --&gt;

&lt;p&gt;吐槽下图中的名称“第一类错误”、“第二类错误”，我最初是在大学上概率论课时见到它们的，有道选择题问某某错误是第一类还是第二类错误，到现在我也没记住哪个指false negative，哪个指false positive，也不想记住了，这个在编程中叫magic number。高数里类似反人类的还有“第一类间断点”、“第二类间端点”，“第一型积分”、“第二型积分”。&lt;/p&gt;

&lt;h2 id=&quot;11-f1&quot;&gt;1.1 F1&lt;/h2&gt;
&lt;p&gt;比较两个模型性能时，往往其中一个的recall相对较高而precision相对较低，这也可以理解，召回的多了，可能增加误召回的几率。如果非要比较两个模型不可呢？就需要用一个指标比较两者，F1就是这样产生的。&lt;/p&gt;

&lt;p&gt;F1定义为recall和precision的调和平均数，一个自然的问题就是为什么选择调和平均数而不是普通的平均数？甚至为什么不是平方平均数（也叫RMS, root mean square）、几何平均数？其实还真有用几何平均数的，上面图片中的 Fowlkes–Mallows index [3] 就是。这四种平均数我记得在高中学的，有个平均数不等式，不过一直没有记住哪个是哪个以及大小关系，在之后的工作中时常会碰到它们，比如音频audio level需要算PCM的平方平均数；评估视频编码效果的PSNR指标需要算残差的平方平均数。&lt;/p&gt;

&lt;p&gt;问AI得知有个统一的形式叫“幂平均数”，这样就好记了。定义如下，值域在x和y之间，p越大，值越大。&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;p趋近负无穷时是min(x, y)&lt;/li&gt;
  &lt;li&gt;p取-1是调和平均数；&lt;/li&gt;
  &lt;li&gt;p趋近0时是 $1^\infty $型极限，结果是几何平均数，求极限过程可以问下AI；&lt;/li&gt;
  &lt;li&gt;p取1时是算术平均数；&lt;/li&gt;
  &lt;li&gt;p取2时是平方平均数；&lt;/li&gt;
  &lt;li&gt;p趋近正无穷时是max(x, y)。&lt;/li&gt;
&lt;/ul&gt;

\[M_p(x, y) = \left( \frac{x^p+y^p}{2} \right)^{1/p}\]

&lt;p&gt;这就明白了为什么用调和平均数或几何平均数，它们“偏向”于较小值，如果其中一个是0，结果则是0，而p大于0的平均数不是这样。&lt;/p&gt;

&lt;p&gt;至于F1和Fowlkes–Mallows index的适用场景，网上只是说前者适用于分类（有监督），后者适用于聚类（无监督），不知道为什么，问了AI也只是一直说what没说why。这个问题 &lt;a href=&quot;https://datascience.stackexchange.com/questions/36817/why-is-the-f-measure-preferred-for-classification-tasks&quot; target=&quot;_blank&quot;&gt;Why is the F-measure preferred for classification tasks?&lt;/a&gt; 下的回答认为是靠经验，我也赞同，没有太多理由，选择哪个指标主观性挺大的，这两个函数的图像长得差不多，只不过F1更“偏向”较小值，看起来更“瘦”一点。&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;../assets/pic/ml/f1.png&quot; alt=&quot;image.png&quot; /&gt;&lt;/p&gt;

&lt;p style=&quot;text-align: center&quot;&gt;
&lt;a href=&quot;https://echarts.apache.org/examples/en/editor.html?c=surface-wave&amp;amp;gl=1&amp;amp;code=OYfQHiC2CWB2AEBeeAGA3AKFBSBDMS8AjJliAJ5RyHpmV4HIkZkAOATgKYAm0AxgBcQALyoJktUBx78hohoWZsA9nCGwArpABGndoQDstCAGcBnVoQAU2KPngBaeLZiwAlPAD0zkK1Wx1LV12TEozC2tQensnKLEPbyl_QJ09UmVWAWhlcXgAbwx4eAFlZQAbLNYALnyAXwAaQvhtXD4Aa2B2ZQ1YbgBhcuV2GoByAGIAMymRxqKAN2gTDVwygFlcavymos9vEwALZQB3GomVk05ZovheSE5YE2zYGoAmK6LXGqkuXkERMXe8AYX18P1k_wYgLgACVcLBgJwagVrtc-INhvAANrbFHwcYAZiI-IAbABOACsMxxKPGABZyQZydpaVTcddxgZabhuNwiKy2XixrhtNxSZxSfy2eNOCgJviJgAOSW48ZTKbaCbKmmTTgy0koLXsybcXCcYl8wHaia04ncWn4w1FcbcAz4lAvAyOwW4ckod3EkbU-AAXRxtSaDSaYAAgmBFviACJInECcisRF4uYrDScQNFSNFcix-NJrYo1Pp0ZZso5vPwAvwYTFkyJ5PltMZkbV2s43ZA_A1IiAvvwEysMrQAQAOSCeleEaunWg3FbZeuC04RwGAS6ZTbuL7HGUACtOIInqMhgJDp0Nvt-HX873vM1lGAABKcaDAfYCGq0lAFxYIoLnYaBOBMGpsRRZFcQrTslnYM4-FzS14COaAuAmdhcDufc2RHA5jlOc5OCDBsURHa4Dm5OBgFGNEyiGQ1OAAR2WLIcnw3EwG4tlPh8HA4DQlFgUEuwwBE6jzE2UwZKDfMpPIPjcQEuJXCkj4Bx8aJJIU6SLBqMJ5IFespOEU4enPHJ4CsST4HIDxYNMvs0QeAR4FYFBCHWa8ADo_COKw3mIckPAAKngXz9gC44rCIFB6kcUkiD87zvBeFA3EwUydhfeAuAEDR2AQaK_JMVj2AEOz4EixyctyyxkEcZhcoKzgipKqLcH8wKrCsMq-vs1gPAAam63q4vIJKRoSeAQqILxPOy_S8vazrSp6mLHlgGrIrKgAFABJCKJu2uArHIWqzr846VtM8M2Ue65ntDWo0CAA&quot; target=&quot;_blank&quot;&gt;F1图像&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;../assets/pic/ml/geo.png&quot; alt=&quot;image.png&quot; /&gt;&lt;/p&gt;

&lt;p style=&quot;text-align: center&quot;&gt;
&lt;a href=&quot;https://echarts.apache.org/examples/en/editor.html?c=surface-wave&amp;amp;gl=1&amp;amp;code=OYfQHiC2CWB2AEBeeAGA3AKFBSBDMS8AjJliAJ5RyHpmV4HIkZkAOATgKYAm0AxgBcQALyoJktUBx78hohoWZsA9nCGwArpABGndoQDstCAGcBnVoQAU2KPngBaeLZiwAlPAD0zkK1Wx1LV12TEozC2tQensnKLEPbyl_QJ09UmVWAWhlcXgAbwx4eAFlZQAbLNYALnyAXwAaQvhtXD4Aa2B2ZQ1YbgBhcuV2GoByAGIAMymRxqKAN2gTDVwygFlcavymos9vEwALZQB3GomVk05ZovheSE5YE2zYGoAmK6LXGqkuXkERMXe8AYX18P1k_wYgLgACVcLBgJwagVrtc-INhvAANrbFHwcYAZiI-IAbABOACsMxxKPGABZyQZydpaVTcddxgZabhuNwiKy2XixrhtNxSZxSfy2eNOCgJviJgAOSW48ZTKbaCbKmmTTgy0koLXsybcXCcYl8wHaia04ncWn4w1FcbcAz4lAvAyOwW4ckod3EkbU-AAXRxtSaDSaYAAgmBFviACJInECcisRF4uYrDScQNFSNFcix-NJrYo1Pp0ZZso5vPwAvwYTFkyJ5PltMZkbV2s43ZA_A1IiAvvwEysMrQAQAOSCeleEaunWg3FbZeuC04RwGAS6ZTbuL7HGUACtOIInqMhgJDp0Nvt-HX873vM1lGAABKcaDAfYCGq0lAFxYIoLnYaBOBMGpsRRZFcQrTslnYM4-FzS14COaAuAmdhcDufc2RHA5jlOc5OCDBsURHa4Dm5OBgFGNEyiGQ1OAAR2WLIcnw3EwG4tlPh8HA4DQlFgUEuwwBE6jzE2UwZKDfMpPIPjcQEuJXCkj4Bx8aJJIU6SLBqMJ5IFespOEU4enPHJ4CsST4HIDxYNMvs0QeAR4FYFBCHWa8ADo_COKw3mIckPAAKngXz9gC44rCIFB6kcUkiD87zvBeFA3EwUzcS4AQNHYBBor8kxWPYAQ7PgSLHJylzvEsZB4AVF5mFyrxvHywritwfzAqsKwSv6-zWA8ABqKLepi_ryCS0aEngEKiC8Tzsv0nZOs4Aqism_zHlgKrIpKgAFABJCLdpi_arHIarLr8s61tM8M2Re643tDWo0CAA&quot; target=&quot;_blank&quot;&gt;Fowlkes–Mallows index图像&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;这两幅图像是用ECharts画的，可以点击进去拖动旋转着看，如丝般顺滑，比Python plot UI上更好看，常见的图可以替代MATLAB了，值得一提的是，这个是国产的为数不多的优秀开源项目。&lt;/p&gt;

&lt;p&gt;最后，F1可扩展到F-$\alpha$，$\alpha$代表precision和recall的权重比例，我觉得这个主观性比较大。&lt;/p&gt;

&lt;h2 id=&quot;12-p-r曲线&quot;&gt;1.2 P-R曲线&lt;/h2&gt;
&lt;p&gt;P-R曲线的纵轴、横轴是precision、recall，如何获得这么多点呢？下面这篇文章[4]说得很清楚，我转载过来。两个指标越大越好，曲线围成的面积越大越好。&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;img src=&quot;../assets/pic/ml/pr_data.webp&quot; alt=&quot;image&quot; /&gt;&lt;/p&gt;

  &lt;p&gt;Inst#是样本序号，图中有20个样本。Class是ground truth 标签，p是positive样本（正例）,n当然就是negative（负例） score是我的分类器对于该样本属于正例的可能性的打分。因为一般模型输出的不是0,1的标注，而是小数，相当于置信度。
然后设置一个从高到低的阈值y，大于等于阈值y的被我正式标注为正例，小于阈值y的被我正式标注为负例。
显然，我设置n个阈值，我就能得到n种标注结果，评判我的模型好不好使。
比如阈值0.9，只有第一个样本被我判断为正例，那么我的查准率precision就是100%,但是查全率recall就是10%。
阈值0.1，所有样本都被我判断为正例，查全率是100%，查准率就是50%
最后我能得到若干对precision，recall值(P,R)  :    (1, 0.1),… ,(0.5,1),将这若干对花在图上，再连接起来就是这个pr曲线了&lt;/p&gt;

  &lt;p&gt;&lt;img src=&quot;../assets/pic/ml/pr_image.webp&quot; alt=&quot;image&quot; /&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h1 id=&quot;2-recall--specificity&quot;&gt;2. recall &amp;amp; specificity&lt;/h1&gt;

&lt;p&gt;&lt;span style=&quot;color: red;&quot;&gt;recall和precision没有考虑 true negative 的数量，它适用于大多数是negative（阴性）的场景&lt;/span&gt;，比如对一个社区的居民做肿瘤筛查，大多数人是健康的；对网民发布的内容做安全审核，大部分内容是安全的。而有的场景positive和negative量级差不多，可以用 specificity(true negative rate) 代替 precision 作为性能指标。&lt;/p&gt;

&lt;h2 id=&quot;21-roc曲线&quot;&gt;2.1 ROC曲线&lt;/h2&gt;

&lt;p&gt;ROC (Receiver operating characteristic) 曲线考虑的是 recall 和 specificity，但它定义的纵轴、横轴是recall、false positve rate(即 1 - specificity)，我第一眼看到ROC曲线不太习惯，它是“反过来”画的，如果横轴是specificity，也就是把x变为1-x，沿x=1/2轴对称变换下，就和P-R曲线一样自然了。而且我觉得specificity和recall才是对应的，表示两个类别各自判别正确的比例，&lt;span style=&quot;color: red;&quot;&gt;ROC适用于positive和negative“平等”的场景&lt;/span&gt;。&lt;/p&gt;

&lt;p&gt;曲线下方的面积AUC (area under curve) 即积分的含义、曲线绘制方法和P-R曲线类似就不多说了。将上面的例子画出两个曲线，为了便于对比，第二个是Specificity-Recall曲线，与ROC曲线等价。P-R曲线往往不是单调的，而ROC是单调的，可以实操算下数据理解。&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;../assets/pic/ml/curve.png&quot; alt=&quot;image&quot; /&gt;&lt;/p&gt;

&lt;p style=&quot;text-align: center&quot;&gt;
&lt;a href=&quot;https://docs.qq.com/sheet/DUWRTSW9DakRZc2R2&quot; target=&quot;_blank&quot;&gt;详细数据和曲线对比&lt;/a&gt;
&lt;/p&gt;

&lt;h1 id=&quot;3-multi-class与multi-label模型&quot;&gt;3. multi-class与multi-label模型&lt;/h1&gt;

&lt;p&gt;上面说的都是二分类任务，结果只有positive和negative，现实中常遇到 multi-class(多分类)任务，比如判断一张动物图片是猫、狗还是猪。评价方法可以看下[5] ，简而言之就是平等对待每类（与ROC类似），“降维”到二分类上，还是用上面的方法。每个分类指标计算后可以使用 macro-average（宏平均）最终算出一个分数，如果类别不均可加权。&lt;/p&gt;

&lt;p&gt;还有multi-label（多标签）任务，比如判断一篇文章的类型，可能同时有“算法”、“存储”、“操作系统”几个标签。参考 [6] 。&lt;/p&gt;

&lt;p&gt;参考资料：&lt;/p&gt;

&lt;p&gt;[1] 汽车召回 &lt;a href=&quot;https://www.samrdprc.org.cn/qczh/gnzhqc/&quot; target=&quot;_blank&quot;&gt;https://www.samrdprc.org.cn/qczh/gnzhqc/&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;[2] 性能度量指标表格 &lt;a href=&quot;https://en.wikipedia.org/wiki/Precision_and_recall#Definition&quot; target=&quot;_blank&quot;&gt;https://en.wikipedia.org/wiki/Precision_and_recall#Definition&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;[3] 综述类 Classification assessment methods
&lt;a href=&quot;https://www.emerald.com/insight/content/doi/10.1016/j.aci.2018.08.003/full/html&quot; target=&quot;_blank&quot;&gt;https://www.emerald.com/insight/content/doi/10.1016/j.aci.2018.08.003/full/html&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;[4] P-R曲线点的获取 &lt;a href=&quot;https://cloud.tencent.com/developer/article/2039361 &quot; target=&quot;_blank&quot;&gt;https://cloud.tencent.com/developer/article/2039361 &lt;/a&gt;&lt;/p&gt;

&lt;p&gt;[5] multi-class &lt;a href=&quot;https://zhuanlan.zhihu.com/p/147663370&quot; target=&quot;_blank&quot;&gt;https://zhuanlan.zhihu.com/p/147663370&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;[6] multi-label &lt;a href=&quot;https://zhuanlan.zhihu.com/p/270458779&quot; target=&quot;_blank&quot;&gt;https://zhuanlan.zhihu.com/p/270458779&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;[7] 谷歌机器学习教程：&lt;a href=&quot;https://developers.google.com/machine-learning/crash-course?hl=zh-cn&quot; target=&quot;_blank&quot;&gt;https://developers.google.com/machine-learning/crash-course?hl=zh-cn&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;[8] 声压 &lt;a href=&quot;https://en.wikipedia.org/wiki/Sound_pressure#Sound_pressure_level&quot; target=&quot;_blank&quot;&gt;https://en.wikipedia.org/wiki/Sound_pressure#Sound_pressure_level&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;[9] PCM audio level &lt;a href=&quot;https://datatracker.ietf.org/doc/html/rfc6465#appendix-A.1&quot; target=&quot;_blank&quot;&gt;https://datatracker.ietf.org/doc/html/rfc6465#appendix-A.1&lt;/a&gt;&lt;/p&gt;
</description>
        <pubDate>Wed, 14 May 2025 00:00:00 +0000</pubDate>
        <link>https://justme0.com//archive/ml-metric.html</link>
        <guid isPermaLink="true">https://justme0.com//archive/ml-metric.html</guid>
        
        
      </item>
    
      <item>
        <title>WebRTC 浏览器端如何抓取和解密 SRTP</title>
        <description>&lt;p&gt;WebRTC 默认使用加密协议 SRTP 传输数据，抓包时看不到明文，不便于排查问题。&lt;/p&gt;

&lt;p&gt;一种方法是下载开发版浏览器关闭加密选项，需要通讯的对端支持；&lt;/p&gt;

&lt;p&gt;另一种方法是打开浏览器的 debug 选项，dump SRTP 解密后的 RTP 数据，下面先介绍这种方法。&lt;/p&gt;

&lt;h1 id=&quot;1-dump-rtp-明文&quot;&gt;1. dump RTP 明文&lt;/h1&gt;
&lt;p&gt;以 Windows 为例，&lt;strong&gt;关闭所有浏览器实例后&lt;/strong&gt;，cmd下使用下面的选项打开浏览器，浏览器路径换成你的。&lt;/p&gt;
&lt;div class=&quot;language-batch highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;s2&quot;&gt;&quot;C:\Program Files\Google\Chrome\Application\chrome.exe&quot;&lt;/span&gt; &lt;span class=&quot;na&quot;&gt;--enable-logging --v&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;na&quot;&gt;--force-fieldtrials&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;kd&quot;&gt;WebRTC&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;-Debugging-RtpDump/Enabled&lt;/span&gt;/
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;其他平台打开日志的方法类似，详见 &lt;a href=&quot;https://support.google.com/chrome/a/answer/6271282#zippy=%2Cwindows%2Cmac%2Clinux&quot; target=&quot;_blank&quot;&gt;https://support.google.com/chrome/a/answer/6271282#zippy=%2Cwindows%2Cmac%2Clinux&lt;/a&gt; （移动平台待补充），Windows上的日志路径是 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;%LOCALAPPDATA%\Google\Chrome\User Data&lt;/code&gt;，也可以使用环境变量 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;CHROME_LOG_FILE&lt;/code&gt; 或选项例如 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;--log-file=&quot;C:\\tmp\\testchrome.log&quot;&lt;/code&gt; 指定。Windows上cmd和PowerShell语法不同，上面的命令是在cmd下运行的。&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;打开试验性选项RTP dump （来源 &lt;a href=&quot;https://source.chromium.org/chromium/chromium/src/+/main:third_party/webrtc/g3doc/field-trials.md&quot; target=&quot;_blank&quot;&gt;https://source.chromium.org/chromium/chromium/src/+/main:third_party/webrtc/g3doc/field-trials.md&lt;/a&gt; ，浏览器所有选项文档 &lt;a href=&quot;https://peter.sh/experiments/chromium-command-line-switches/&quot; target=&quot;_blank&quot;&gt;https://peter.sh/experiments/chromium-command-line-switches/&lt;/a&gt; ）。&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;!-- more --&gt;

&lt;p&gt;浏览器在SRTP模块读取该选项，在RTP、RTCP加密前和SRTP、SRTCP解密后共4处dump，这样将明文RTP和RTCP打印到日志。&lt;/p&gt;
&lt;div class=&quot;language-c++ highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;SrtpSession&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;::&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;SrtpSession&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;webrtc&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;::&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;FieldTrialsView&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;amp;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;field_trials&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;dump_plain_rtp_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;field_trials&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;IsEnabled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;WebRTC-Debugging-RtpDump&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;p&quot;&gt;...&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;// Logs the unencrypted packet in text2pcap format. This can then be&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;// extracted by searching for RTP_DUMP&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;//   grep RTP_DUMP chrome_debug.log &amp;gt; in.txt&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;// and converted to pcap using&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;//   text2pcap -D -u 1000,2000 -t %H:%M:%S. in.txt out.pcap&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;// The resulting file can be replayed using the WebRTC video_replay tool and&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;// be inspected in Wireshark using the RTP, VP8 and H264 dissectors.&lt;/span&gt;
&lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;SrtpSession&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;::&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;DumpPacket&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;buf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;bool&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;outbound&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;kt&quot;&gt;int64_t&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;time_of_day&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rtc&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;::&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;TimeUTCMillis&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;24&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3600&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
  &lt;span class=&quot;kt&quot;&gt;int64_t&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hours&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;time_of_day&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3600&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
  &lt;span class=&quot;kt&quot;&gt;int64_t&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;minutes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;time_of_day&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;60&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;60&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
  &lt;span class=&quot;kt&quot;&gt;int64_t&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seconds&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;time_of_day&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;60&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
  &lt;span class=&quot;kt&quot;&gt;int64_t&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;millis&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;time_of_day&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;RTC_LOG&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;LS_VERBOSE&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;&lt;/span&gt;
                      &lt;span class=&quot;o&quot;&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;outbound&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;?&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;O&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;I&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot; &quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;::&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;setfill&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sc&quot;&gt;&apos;0&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                      &lt;span class=&quot;o&quot;&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;::&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;setw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hours&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;:&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;::&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;setfill&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sc&quot;&gt;&apos;0&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                      &lt;span class=&quot;o&quot;&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;::&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;setw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;minutes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;:&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;::&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;setfill&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sc&quot;&gt;&apos;0&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                      &lt;span class=&quot;o&quot;&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;::&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;setw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seconds&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;.&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;::&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;setfill&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sc&quot;&gt;&apos;0&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                      &lt;span class=&quot;o&quot;&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;::&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;setw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;millis&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot; &quot;&lt;/span&gt;
                      &lt;span class=&quot;o&quot;&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;000000 &quot;&lt;/span&gt;
                      &lt;span class=&quot;o&quot;&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rtc&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;::&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hex_encode_with_delimiter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
                             &lt;span class=&quot;n&quot;&gt;absl&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;::&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;string_view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;char&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;buf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;sc&quot;&gt;&apos; &apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                      &lt;span class=&quot;o&quot;&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot; # RTP_DUMP&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;from &lt;a href=&quot;https://source.chromium.org/chromium/chromium/src/+/main:third_party/webrtc/pc/srtp_session.cc;l=123?q=%22WebRTC-Debugging-RtpDump%22&quot; target=&quot;_blank&quot;&gt;https://source.chromium.org/chromium/chromium/src/+/main:third_party/webrtc/pc/srtp_session.cc;l=123?q=%22WebRTC-Debugging-RtpDump%22&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;如上面代码注释中所说，接下来执行&lt;/p&gt;
&lt;div class=&quot;language-bash highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nb&quot;&gt;grep &lt;/span&gt;RTP_DUMP chrome_debug.log &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;in&lt;/span&gt;.txt
text2pcap &lt;span class=&quot;nt&quot;&gt;-D&lt;/span&gt; &lt;span class=&quot;nt&quot;&gt;-u&lt;/span&gt; 1000,2000 &lt;span class=&quot;nt&quot;&gt;-t&lt;/span&gt; %H:%M:%S. &lt;span class=&quot;k&quot;&gt;in&lt;/span&gt;.txt out.pcap
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;推荐安装 Wireshark，在安装目录带了 text2pcap 工具。&lt;/p&gt;

&lt;p&gt;打开 out.pcap，解析为RTP，在【编辑】-&amp;gt;【首选项】-&amp;gt;【协议】设置OPUS等编码的RTP payload，可以看到明文包。
&lt;img src=&quot;../assets/pic/srtp/srtp.webp&quot; alt=&quot;image.png&quot; /&gt;&lt;/p&gt;

&lt;p&gt;在Wireshark中的音视频抓包如何保存成媒体文件？开源项目 h264extractor [1] 支持H.264和OPUS的提取。将Lua脚本放到Wireshark安装目录的plugins目录即可（旧版的Wireshark安装Lua插件相对麻烦），我在Windows提取OPUS时报了错，提交了PR给这个项目。本来想自己写工具解析包的，后来看了这个工具，其实用Wireshark Lua插件更加合适，跨平台，方便调用Wireshark提供解析包的接口。&lt;/p&gt;

&lt;p&gt;提取的H.264可直接播放，但是OPUS是帧长（4字节）+帧数据的形式保存的，不能直接播放，写了一个工具 opus_muxer [2] 将这种形式封装为WebM方便播放。&lt;/p&gt;

&lt;p&gt;后续还可使用 WebRTC video_replay [3] 工具 replay 音视频，待补充。&lt;/p&gt;

&lt;h1 id=&quot;2-关闭srtp方法&quot;&gt;2. 关闭SRTP方法&lt;/h1&gt;

&lt;p&gt;需要使用 Chromium、开发版Chrome或金丝雀版Chrome，提供了选项&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;--disable-webrtc-encryption&lt;/code&gt; ，可以看到浏览器在STUN探测成功后就发RTP包了，绿色的是带use-candidate的STUN包，没有等回包就发媒体包了。这种方式需要PeerConnection对端也支持不加密，在SDP中协商，调试第三方系统时可能不支持。&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;../assets/pic/srtp/no.webp&quot; alt=&quot;image.png&quot; /&gt;&lt;/p&gt;

&lt;p&gt;如果要保存为音视频文件，可以参考第1节说的工具。&lt;/p&gt;

&lt;h1 id=&quot;后记&quot;&gt;后记&lt;/h1&gt;

&lt;p&gt;端上dump明文音视频用于调试本身是很朴素的想法，如果是native端可操控性强，但是Web端就需要浏览器内部支持。另外如果是服务端伪装的PeerConnection对端，也可在服务器上dump明文。&lt;/p&gt;

&lt;p&gt;在浏览器解密SRTP后获取音视频数据，同样的想法理论上也可以应用到点播或直播，将音视频在HTTPS(TLS)解密后或H5 video标签播放前将音视频数据dump出来。&lt;/p&gt;

&lt;p&gt;参考资料&lt;/p&gt;

&lt;p&gt;[1] 解析抓包保存音视频文件 &lt;a href=&quot;https://github.com/volvet/h264extractor&quot; target=&quot;_blank&quot;&gt;https://github.com/volvet/h264extractor&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;[2] 封装 OPUS raw frame &lt;a href=&quot;https://github.com/Justme0/opus_muxer&quot; target=&quot;_blank&quot;&gt;https://github.com/Justme0/opus_muxer&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;[3] video_replay 工具 &lt;a href=&quot;https://webrtchacks.com/video_replay/&quot; target=&quot;_blank&quot;&gt;https://webrtchacks.com/video_replay/&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;[4] Firefox 调试加密包 &lt;a href=&quot;https://stackoverflow.com/questions/53292936/analyzing-rtp-packets-from-browsers-webrtc-stream-using-wireshark-or-similar-to&quot; target=&quot;_blank&quot;&gt;https://stackoverflow.com/questions/53292936/analyzing-rtp-packets-from-browsers-webrtc-stream-using-wireshark-or-similar-to&lt;/a&gt;&lt;/p&gt;
</description>
        <pubDate>Thu, 27 Jun 2024 00:00:00 +0000</pubDate>
        <link>https://justme0.com//archive/srtp.html</link>
        <guid isPermaLink="true">https://justme0.com//archive/srtp.html</guid>
        
        
      </item>
    
      <item>
        <title>字符编码小结</title>
        <description>&lt;p&gt;记得几年前有次需要写个简单的脚本，开始用的Python碰到中文编码问题，而且Python2和3规则不同，折腾了之后改用Ruby分分钟就搞定了，感觉Ruby的开发效率更高，几乎没有“令人惊讶”的设计；Python以缩进表示层级有时也带来不便，其他语言可以用clang-format自动格式化，也能保持风格的一致。&lt;/p&gt;

&lt;p&gt;Python在AI的生态很好，最近写这块程序碰到&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bytes&lt;/code&gt;和&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;str&lt;/code&gt;转换时字符编码的问题，平常也时常碰到乱码的困惑，比如打开文件或者浏览网页乱码，尝试换一下编码就ok了，但是没有深究原理。这次彻底把字符编码弄清楚了。&lt;/p&gt;

&lt;p&gt;下面说下常见的编码，ASCII, latin-1, Unicode, UTF-8(UTF-16/32)，这几种在Python中常见。&lt;/p&gt;

&lt;!-- more --&gt;

&lt;h1 id=&quot;1-ascii&quot;&gt;1. ASCII&lt;/h1&gt;
&lt;p&gt;首先是熟悉的ASCII，占7bit，很早以前用多余的1bit作校验（《松本行弘的程序世界》中讲了历史），英语世界没有问题。&lt;/p&gt;

&lt;h1 id=&quot;2-latin-1&quot;&gt;2. latin-1&lt;/h1&gt;
&lt;p&gt;欧洲国家 latin-1（也称ISO 8859-1），是ASCII的超集, 每个字符只占一个字节，把剩余的1位用上了。&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;此字符集支持部分于欧洲使用的语言，包括阿尔巴尼亚语、巴斯克语、布列塔尼语、加泰罗尼亚语、丹麦语、荷兰语、法罗语、弗里西语、加利西亚语、德语、格陵兰语、冰岛语、爱尔兰盖尔语、意大利语、拉丁语、卢森堡语、挪威语、葡萄牙语、里托罗曼斯语、苏格兰盖尔语、西班牙语及瑞典语。&lt;/p&gt;

  &lt;p&gt;英语虽然没有重音字母，但仍会标明为ISO/IEC 8859-1编码。除此之外，欧洲以外的部分语言，如南非荷兰语、斯瓦希里语、印尼语及马来语、菲律宾他加洛语等也可使用ISO/IEC 8859-1编码。&lt;/p&gt;

  &lt;p&gt;法语及芬兰语本来也使用ISO/IEC 8859-1来表示。但因它没有法语使用的 œ、Œ、Ÿ 三个字母及芬兰语使用的 Š、š、Ž、ž ，故于1998年被ISO/IEC 8859-15所取代。（ISO 8859-15同时加入了欧元符号）&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p style=&quot;text-align: center&quot;&gt;
&lt;img src=&quot;../assets/pic/latin-1.png&quot; width=&quot;693&quot; /&gt;
&lt;br /&gt;
latin-1 编码表
&lt;/p&gt;

&lt;h1 id=&quot;3-unicode&quot;&gt;3. Unicode&lt;/h1&gt;
&lt;p&gt;还有中文、日语等等，Unicode顾名思义，包括了所有字符，关键要注意的一点是，&lt;font color=&quot;red&quot;&gt;它不是编码方式，它只是字符集&lt;/font&gt;，就是说ISO组织把所有的字符编了个号，到2022年是14万多个字符，它其实和怎么在磁盘存储、网络传输（这两种涉及序列化）编码的方式没有关系。&lt;/p&gt;

&lt;p&gt;有的人可能会想，把这14万个字符用3个字节足以表示了，但是欧美国家的人大部分用不到，每个字符都用3字节浪费了。&lt;/p&gt;

&lt;h1 id=&quot;4-utf-8&quot;&gt;4. UTF-8&lt;/h1&gt;
&lt;p&gt;UTF全称 Unicode Transformation Format，这是一种将Unicode编码的节省空间的方式，不是通通都用3个字节表示字符。我觉得和哈夫曼编码思想很像，前缀不能冲突。下面看下编码。&lt;/p&gt;

&lt;h2 id=&quot;41-编码&quot;&gt;4.1 编码&lt;/h2&gt;
&lt;p&gt;Python中的&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;str&lt;/code&gt;数据类型的每个字符是Unicode（本文都是讲Python3，注意这个坑点：Python2的&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;str&lt;/code&gt;和Python3的&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;str&lt;/code&gt;不一样，和Python3的&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bytes&lt;/code&gt;是一样的），编码指用某种编码格式将一个字符编码成多个字节，ASCII码和 latin-1 都是一个字符对应一个字节，UTF-8一个字符对应多个字节。&lt;/p&gt;

&lt;p&gt;利用前缀思想，我开始自己设计了一个方式，比UTF-8更节省空间：&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;字节数&lt;/th&gt;
      &lt;th&gt;UTF-8&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;1&lt;/td&gt;
      &lt;td&gt;0xxxxxxx 利用7bit&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;2&lt;/td&gt;
      &lt;td&gt;10xxxxxx xxxxxxxx 利用 14bit&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;3&lt;/td&gt;
      &lt;td&gt;110xxxxx xxxxxxxx xxxxxxxx 利用 21bit&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;4&lt;/td&gt;
      &lt;td&gt;1110xxxx xxxxxxxx xxxxxxxx xxxxxxxx 利用 28bit&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;n&lt;/td&gt;
      &lt;td&gt;利用 &lt;font color=&quot;red&quot;&gt;7n bit&lt;/font&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;前面n-1个1开头，指明本字符占n个字节，能表示7n个bit。&lt;/p&gt;

&lt;p&gt;而UTF-8只能表示5n+1个bit（本式的n是UTF-8开头1的个数，ASCII例外），规则如下，乍一看规则比我设计的要复杂，其规则是 &amp;gt;=2字节的，有几个1开头就表示共占几个字节，从第2个字节开始固定以10开头。&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;字节数&lt;/th&gt;
      &lt;th&gt;Unicode&lt;/th&gt;
      &lt;th&gt;UTF-8&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;1&lt;/td&gt;
      &lt;td&gt;U+0000 ~ U+007F&lt;/td&gt;
      &lt;td&gt;0xxxxxxx 利用7bit&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;2&lt;/td&gt;
      &lt;td&gt;U+0080 ~ U+07FF&lt;/td&gt;
      &lt;td&gt;110xxxxx 10xxxxxx 利用 11bit&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;3&lt;/td&gt;
      &lt;td&gt;U+0800 ~ U+FFFF&lt;/td&gt;
      &lt;td&gt;1110xxxx 10xxxxxx 10xxxxxx 利用 16bit&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;4&lt;/td&gt;
      &lt;td&gt;U+10000 ~ U+10FFFF&lt;/td&gt;
      &lt;td&gt;11110xxx 10xxxxxx 10xxxxxx 10xxxxxx 利用 21bit&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;n&lt;/td&gt;
      &lt;td&gt; &lt;/td&gt;
      &lt;td&gt;利用 &lt;font color=&quot;red&quot;&gt;5n+1 bit&lt;/font&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;它为什么这么复杂呢？其实它还考虑了实际场景，我的设计需要严丝合缝，从头开始解析不能出一点错，而实际场景可能文件开始有一点错，希望能从中途开始最大程度地解析，这就是为什么UTF-8从第2个字节开始固定以10开头的原因了，它和ASCII不冲突，也与前缀（110, 1110 …）不冲突，不魁是 Robe Pike 和 Ken Thompson 设计的。&lt;/p&gt;

&lt;p&gt;另外注意 &lt;font color=&quot;red&quot;&gt;latin-1 和 Unicode 编码方式不兼容&lt;/font&gt;。&lt;/p&gt;

&lt;p&gt;例如，重音字符会在latin-1字符集和Unicode字符集中同时存在，但是通过latin-1和Unicode编码方式编出来的字节流是不一样的，注意，虽然Unicode字符集是包含了latin-1字符集，但是不代表UTF-8编码方式兼容latin-1编码方式。因为Unicode字符集中除了ASCII字符集外，都是采用多字节的编码方式，而latin-1一律采用单字节的方式。&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;s&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&apos;Äè&apos;&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;encode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&apos;utf-8&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;encode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&apos;latin-1&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;sa&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\xc3\x84\xc3\xa8&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&apos;&lt;/span&gt;
&lt;span class=&quot;sa&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\xc4\xe8&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&apos;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;UTF-16/32思想和UTF-8差不多，就是基础字节用了2B/4B，不太流行。&lt;/p&gt;

&lt;h2 id=&quot;42-解码&quot;&gt;4.2 解码&lt;/h2&gt;

&lt;p&gt;将字节流（二进制流/&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bytes&lt;/code&gt;）按某种编码方式“解释”，例如下面的b变量（字节流）含6个字节。&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;sa&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\xe6\x8e\x92\xe7\x90\x83&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&apos;&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;s1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;decode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;encoding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&apos;utf-8&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;s2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;decode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# 用系统默认编码方式，通常是UTF-8?
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;s3&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;decode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;encoding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&apos;latin-1&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# 每个字符一个字节，强行“解释”，仔细看下面的乱码，有6个
&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;s1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;s2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;s3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;排球&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;排球&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;æŽ&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;’&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ç&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ƒ&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;s&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&apos;AÄBèC&apos;&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Unicode 5 字符
&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;open&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&apos;utf-8data&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&apos;w&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;encoding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&apos;utf-8&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
   &lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;write&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# UTF-8编码写磁盘，7个字节（观察第二、第四个字符特殊，各占两字节）
&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;open&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&apos;utf-8data&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&apos;rb&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
   &lt;span class=&quot;n&quot;&gt;byte_str&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;read&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;byte_str&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;byte_str&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;decode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;encoding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&apos;utf-8&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;sa&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&apos;A&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\xc3\x84&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\xc3\xa8&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;C&apos;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# A B C 正常打印，第二、第四个字符特殊，打印十六进制
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;AÄBèC&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h1 id=&quot;5-文件头magic-number&quot;&gt;5. 文件头magic number&lt;/h1&gt;
&lt;p&gt;用以上各种编码保存成文件，再打开时文本编辑器怎么“解释”呢？用文件头magic number区分。&lt;/p&gt;

&lt;p&gt;打开“记事本”程序 notepad.exe，新建一个文本文件，内容就是一个“严”字（Unicode U+4E25），依次采用ANSI，Unicode，Unicode big endian和UTF-8编码方式保存。&lt;/p&gt;

&lt;p&gt;然后，用文本编辑软件 UltraEdit 中的“十六进制功能”，观察该文件的内部编码方式。&lt;/p&gt;

&lt;p&gt;1）ANSI：对于英文文件是ASCII编码，对于简体中文文件是GB2312编码（只针对 Windows 简体中文版，如果是繁体中文版会采用 Big5 码）&lt;/p&gt;

&lt;p&gt;文件的编码就是两个字节D1 CF，这正是严的 GB2312 编码，这也暗示 GB2312 是采用大头方式存储的。&lt;/p&gt;

&lt;p&gt;2）Unicode：notepad.exe 使用的 UCS-2 编码方式，即直接用两个字节存入字符的 Unicode 码，这个选项用的 little endian 格式。&lt;/p&gt;

&lt;p&gt;编码是四个字节FF FE 25 4E，其中FF FE表明是小头方式存储，真正的编码是4E25。&lt;/p&gt;

&lt;p&gt;3）Unicode big endian：编码是四个字节FE FF 4E 25，其中FE FF表明是大头方式存储。&lt;/p&gt;

&lt;p&gt;4）UTF-8：编码是六个字节EF BB BF E4 B8 A5，前三个字节EF BB BF表示这是UTF-8编码，后三个E4B8A5就是严的具体编码，它的存储顺序与编码顺序是一致的：&lt;/p&gt;

&lt;p&gt;“严”的 Unicode 4E25 即 0100 1110 0010 0101 用 UTF-8  1110xxxx 10xxxxxx 10xxxxxx  方式存储填充：1110 0100 10 1110 00 10 100101 即 E4 B8 A5。&lt;/p&gt;

&lt;p&gt;参考资料&lt;/p&gt;

&lt;p&gt;[1] latin-1 介绍 https://en.wikipedia.org/wiki/ISO/IEC_8859-1&lt;/p&gt;

&lt;p&gt;[2] 文中程序示例来自 https://zhuanlan.zhihu.com/p/31920527&lt;/p&gt;

&lt;p&gt;[3] 文件头一节来自 https://blog.csdn.net/Deft_MKJing/article/details/79460485&lt;/p&gt;
</description>
        <pubDate>Sat, 03 Jun 2023 00:00:00 +0000</pubDate>
        <link>https://justme0.com//archive/utf-8.html</link>
        <guid isPermaLink="true">https://justme0.com//archive/utf-8.html</guid>
        
        
      </item>
    
      <item>
        <title>WebRTC TURN 协议源码分析</title>
        <description>&lt;p&gt;WebRTC 是2011年谷歌开源的媒体框架，可以在浏览器中进行实时音视频通信，它是为P2P通信设计的，开发者也可以自己搭建服务器作为通信的一端。在下面这些网络条件限制严格的场景下不能直接建立通信，需要借助中转服务器TURN（Traversal Using Relays around NAT）转发。&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;一端是对称型NAT，另一端是端口限制锥形NAT或者也是对称型NAT&lt;/strong&gt;，无法建立P2P。这个工具可以检测自己网络的NAT类型 &lt;a href=&quot;https://github.com/aarant/pynat&quot; target=&quot;_blank&quot;&gt;https://github.com/aarant/pynat&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;对网络出口限制严格的环境，比如银行、政府单位，要求访问的外网IP地址需要加到其网关白名单。可以独立部署TURN服务器，将TURN的公网IP地址加到白名单。&lt;/li&gt;
  &lt;li&gt;对安全要求极端严格的防火墙，不允许UDP通信，甚至只允许TLS over 443端口的流量。（来源 &lt;a href=&quot;https://security.stackexchange.com/a/196330&quot; target=&quot;_blank&quot;&gt;https://security.stackexchange.com/a/196330&lt;/a&gt; ）&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;turn-流程分析&quot;&gt;TURN 流程分析&lt;/h1&gt;
&lt;p&gt;协议分为三部分&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;在TURN服务器上创建传输&lt;strong&gt;资源，称为 allocation&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;indication 方式传输数据&lt;/li&gt;
  &lt;li&gt;channel 方式传输数据&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;要注意的是，这两种传输数据的方式是并列关系。三部分的流程时序图如下（可右键打开，放大查看文本格式），client参考WebRTC代码，server参考pion/turn代码。
&lt;!-- more --&gt;&lt;/p&gt;

&lt;p style=&quot;text-align: center&quot;&gt;
&lt;img src=&quot;../assets/pic/turn/seq.svg&quot; width=&quot;2000&quot; /&gt;
&lt;br /&gt;
TURN时序图
&lt;/p&gt;

&lt;h1 id=&quot;1-创建-allocation-资源&quot;&gt;1. 创建 allocation 资源&lt;/h1&gt;
&lt;p&gt;allocation是TURN服务器分配给客户端的资源，数据结构如下，列了主要的字段（详见 &lt;a href=&quot;https://github.com/pion/turn/blob/master/internal/allocation/allocation.go#L23&quot; target=&quot;_blank&quot;&gt;https://github.com/pion/turn/blob/master/internal/allocation/allocation.go#L23&lt;/a&gt; ）。以五元组 fiveTuple &amp;lt;clientIP, clientPort, svrIP, svrPort, protocol&amp;gt;标识一个allocation，protocol 最新的RFC文档规定有TCP/UDP/TLS/DTLS，pion暂未支持DTLS，服务端监听端口 svrPort 默认是3478 for TCP/UDP, 5349 for TLS/DTLS。&lt;/p&gt;

&lt;div class=&quot;language-golang highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c&quot;&gt;// FiveTuple is the combination (client IP address and port, server IP&lt;/span&gt;
&lt;span class=&quot;c&quot;&gt;// address and port, and transport protocol (currently one of UDP,&lt;/span&gt;
&lt;span class=&quot;c&quot;&gt;// TCP, or TLS)) used to communicate between the client and the&lt;/span&gt;
&lt;span class=&quot;c&quot;&gt;// server.  The 5-tuple uniquely identifies this communication&lt;/span&gt;
&lt;span class=&quot;c&quot;&gt;// stream.  The 5-tuple also uniquely identifies the Allocation on&lt;/span&gt;
&lt;span class=&quot;c&quot;&gt;// the server.&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;type&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;FiveTuple&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;struct&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
	&lt;span class=&quot;n&quot;&gt;Protocol&lt;/span&gt;
	&lt;span class=&quot;n&quot;&gt;SrcAddr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;DstAddr&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;net&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Addr&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;type&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Allocation&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;struct&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
	&lt;span class=&quot;n&quot;&gt;RelayAddr&lt;/span&gt;           &lt;span class=&quot;n&quot;&gt;net&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Addr&lt;/span&gt;
	&lt;span class=&quot;n&quot;&gt;Protocol&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;Protocol&lt;/span&gt;
	&lt;span class=&quot;n&quot;&gt;TurnSocket&lt;/span&gt;          &lt;span class=&quot;n&quot;&gt;net&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;PacketConn&lt;/span&gt;
	&lt;span class=&quot;n&quot;&gt;RelaySocket&lt;/span&gt;         &lt;span class=&quot;n&quot;&gt;net&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;PacketConn&lt;/span&gt;
	&lt;span class=&quot;n&quot;&gt;fiveTuple&lt;/span&gt;           &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;FiveTuple&lt;/span&gt;
	&lt;span class=&quot;n&quot;&gt;permissionsLock&lt;/span&gt;     &lt;span class=&quot;n&quot;&gt;sync&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;RWMutex&lt;/span&gt;
	&lt;span class=&quot;n&quot;&gt;permissions&lt;/span&gt;         &lt;span class=&quot;k&quot;&gt;map&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;string&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Permission&lt;/span&gt;
	&lt;span class=&quot;n&quot;&gt;channelBindingsLock&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sync&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;RWMutex&lt;/span&gt;
	&lt;span class=&quot;n&quot;&gt;channelBindings&lt;/span&gt;     &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ChannelBind&lt;/span&gt;
	&lt;span class=&quot;n&quot;&gt;lifetimeTimer&lt;/span&gt;       &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;time&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Timer&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p style=&quot;text-align: center&quot;&gt;
&lt;img src=&quot;../assets/pic/turn/1alloc.webp&quot; width=&quot;800&quot; /&gt;
&lt;br /&gt;
allocation结构
&lt;/p&gt;

&lt;p&gt;特别关注数据结构中的 permissions 和 channelBindings 字段，permissions的key是peer端地址，channelBindings是数组，也是以peer端地址标识。下面对照时序图介绍流程。&lt;/p&gt;

&lt;h2 id=&quot;11-stun-bind-request&quot;&gt;1.1 STUN bind request&lt;/h2&gt;
&lt;p&gt;和STUN功能一样，返回client的IP和port，用于告知端上自己的出口地址，收集local candidate，服务端无状态。&lt;/p&gt;

&lt;h2 id=&quot;12-allocation-request&quot;&gt;1.2 allocation request&lt;/h2&gt;
&lt;p&gt;请求分配资源，请求参数中标识了在TURN和peer之间是UDP还是TCP，WebRTC client写死的UDP，注意RFC文档是规范，WebRTC是实现，它没有实现标准中规定的所有功能。从下面的源码可以看出，请求中没有带 MAC 码AttrMessageIntegrity，返回 401 错误码CodeUnauthorized，并返回realm和随机数。这里反错是正常流程，就是为了将服务端的一些参数带会给端上。&lt;/p&gt;

&lt;div class=&quot;language-go highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;authenticateRequest&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;r&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Request&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;stun&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Message&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;callingMethod&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stun&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Method&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;stun&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;MessageIntegrity&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;bool&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;error&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
	&lt;span class=&quot;n&quot;&gt;respondWithNonce&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;:=&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;func&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;responseCode&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stun&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ErrorCode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;stun&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;MessageIntegrity&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;bool&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;error&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
		&lt;span class=&quot;n&quot;&gt;nonce&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;err&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;:=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;buildNonce&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
		&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;err&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!=&lt;/span&gt; &lt;span class=&quot;no&quot;&gt;nil&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
			&lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;no&quot;&gt;nil&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;no&quot;&gt;false&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;err&lt;/span&gt;
		&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

		&lt;span class=&quot;c&quot;&gt;// Nonce has already been taken&lt;/span&gt;
		&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keyCollision&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;:=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;r&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Nonces&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;LoadOrStore&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nonce&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;time&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Now&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;());&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keyCollision&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
			&lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;no&quot;&gt;nil&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;no&quot;&gt;false&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;errDuplicatedNonce&lt;/span&gt;
		&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

		&lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;no&quot;&gt;nil&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;no&quot;&gt;false&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;buildAndSend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;r&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Conn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;r&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;SrcAddr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;buildMsg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;TransactionID&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
			&lt;span class=&quot;n&quot;&gt;stun&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;NewType&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;callingMethod&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stun&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ClassErrorResponse&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
			&lt;span class=&quot;o&quot;&gt;&amp;amp;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;stun&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ErrorCodeAttribute&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Code&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;responseCode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;},&lt;/span&gt;
			&lt;span class=&quot;n&quot;&gt;stun&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;NewNonce&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nonce&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
			&lt;span class=&quot;n&quot;&gt;stun&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;NewRealm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;r&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Realm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
		&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;...&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
	&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

	&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Contains&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;stun&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;AttrMessageIntegrity&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
		&lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;respondWithNonce&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;stun&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;CodeUnauthorized&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
	&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
	&lt;span class=&quot;o&quot;&gt;...&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;端上收到响应后设置realm、随机数，计算MAC码= MD5(username “:” realm “:” SASLprep(password))，下一步会带上MAC码，端上处理回包详见 TurnAllocateRequest::OnAuthChallenge  &lt;a href=&quot;https://source.chromium.org/chromium/chromium/src/+/main:third_party/webrtc/p2p/base/turn_port.cc;l=1439&quot; target=&quot;_blank&quot;&gt;https://source.chromium.org/chromium/chromium/src/+/main:third_party/webrtc/p2p/base/turn_port.cc;l=1439&lt;/a&gt;&lt;/p&gt;

&lt;h2 id=&quot;13-第二次-allocation-request&quot;&gt;1.3 第二次 allocation request&lt;/h2&gt;
&lt;p&gt;端上携带 MAC 码、realm和上一步返回的随机数，再次请求分配 allocation，服务端校验MAC码，ok后创建 Allocation 数据结构，并给 lifetimeTimer 字段赋定时器，资源保活时间默认10分钟，WebRTC 端上会提前一分钟发心跳保活，也就是每9分钟发一次心跳；客户端如果想释放资源，在refresh request请求参数中将lifetime填0，下一节会讲。分配资源后，服务端进程&lt;font color=&quot;red&quot;&gt;bind 一个 UDP port&lt;/font&gt;，用于和peer通信，for 循环等待着从peer收包。&lt;/p&gt;

&lt;div class=&quot;language-go highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Manager&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;CreateAllocation&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fiveTuple&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;FiveTuple&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;turnSocket&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;net&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;PacketConn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;requestedPort&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lifetime&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;time&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Duration&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Allocation&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;error&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
	&lt;span class=&quot;o&quot;&gt;...&lt;/span&gt;
	&lt;span class=&quot;k&quot;&gt;go&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;packetHandler&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
	&lt;span class=&quot;o&quot;&gt;...&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;c&quot;&gt;// 从relay端口（UDP）收包处理&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Allocation&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;packetHandler&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Manager&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
	&lt;span class=&quot;n&quot;&gt;buffer&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;:=&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;make&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([]&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;byte&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rtpMTU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

	&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
		&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;srcAddr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;err&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;:=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;RelaySocket&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ReadFrom&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;buffer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
		&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;err&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!=&lt;/span&gt; &lt;span class=&quot;no&quot;&gt;nil&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
			&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;DeleteAllocation&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fiveTuple&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
			&lt;span class=&quot;k&quot;&gt;return&lt;/span&gt;
		&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

		&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Debugf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;relay socket %s received %d bytes from %s&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
			&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;RelaySocket&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;LocalAddr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;String&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
			&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
			&lt;span class=&quot;n&quot;&gt;srcAddr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;String&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
		&lt;span class=&quot;o&quot;&gt;...&lt;/span&gt;
	&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;14-allocation-refresh-request&quot;&gt;1.4 allocation refresh request&lt;/h2&gt;
&lt;p&gt;请求参数中指定多久(即expire)之后释放资源，如果传0表示立即释放资源，端上定时刷新 expire，也就是定时保活。&lt;/p&gt;

&lt;h1 id=&quot;2-indication-方式传输数据&quot;&gt;2. indication 方式传输数据&lt;/h1&gt;

&lt;p style=&quot;text-align: center&quot;&gt;
&lt;img src=&quot;../assets/pic/turn/2indicate.webp&quot; width=&quot;700&quot; /&gt;
&lt;br /&gt;
indication方式概览 from RFC
&lt;/p&gt;

&lt;h2 id=&quot;21-create-permission&quot;&gt;2.1 create permission&lt;/h2&gt;
&lt;p&gt;用indication方式传数据前，先请求权限。端上add remote candidate时，创建 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TurnEntry&lt;/code&gt; 对象，在构造函数中发送create permission请求，请求参数中携带了peer地址。&lt;/p&gt;

&lt;div class=&quot;language-cpp highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;TurnEntry&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;::&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;TurnEntry&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;TurnPort&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;port&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Connection&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;conn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;channel_id&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;port_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;port&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
      &lt;span class=&quot;n&quot;&gt;channel_id_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;channel_id&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
      &lt;span class=&quot;n&quot;&gt;ext_addr_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conn&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;remote_candidate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;address&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()),&lt;/span&gt;
      &lt;span class=&quot;n&quot;&gt;state_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;STATE_UNBOUND&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
      &lt;span class=&quot;n&quot;&gt;connections_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;({&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;})&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;c1&quot;&gt;// Creating permission for `ext_addr_`.&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;SendCreatePermissionRequest&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;from &lt;a href=&quot;https://source.chromium.org/chromium/chromium/src/+/main:third_party/webrtc/p2p/base/turn_port.cc;l=1764&quot; target=&quot;_blank&quot;&gt;https://source.chromium.org/chromium/chromium/src/+/main:third_party/webrtc/p2p/base/turn_port.cc;l=1764&lt;/a&gt;&lt;/p&gt;

&lt;p style=&quot;text-align: center&quot;&gt;
&lt;img src=&quot;../assets/pic/turn/2.1createPermission.webp&quot; width=&quot;600&quot; /&gt;
&lt;br /&gt;
create permission 抓包
&lt;/p&gt;

&lt;p&gt;服务器收到信令后，在 Allocation 结构体的 permissions map 中增加一个kv，key是peer地址，标识了这个permission，同时创建定时器，超时的话删除这个permission，超时时间5min，最后回包给端上。&lt;/p&gt;

&lt;p&gt;端上收到回包后准备好下次发心跳保活：&lt;/p&gt;

&lt;div class=&quot;language-cpp highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;TurnEntry&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;::&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;OnCreatePermissionSuccess&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;RTC_LOG&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;LS_INFO&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;port_&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ToString&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;: Create permission for &quot;&lt;/span&gt;
                   &lt;span class=&quot;o&quot;&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ext_addr_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ToSensitiveString&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot; succeeded&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
  &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;port_&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;callbacks_for_test_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;port_&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;callbacks_for_test_&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;OnTurnCreatePermissionResult&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;TURN_SUCCESS_RESULT_CODE&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
  &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

  &lt;span class=&quot;c1&quot;&gt;// If `state_` is STATE_BOUND, the permission will be refreshed&lt;/span&gt;
  &lt;span class=&quot;c1&quot;&gt;// by ChannelBindRequest.&lt;/span&gt;
  &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;state_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;STATE_BOUND&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;// Refresh the permission request about 1 minute before the permission&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;// times out.&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;TimeDelta&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;delay&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kTurnPermissionTimeout&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;TimeDelta&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;::&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Minutes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;SendCreatePermissionRequest&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;delay&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ms&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;());&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;RTC_LOG&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;LS_INFO&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;port_&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ToString&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
                     &lt;span class=&quot;o&quot;&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;: Scheduled create-permission-request in &quot;&lt;/span&gt;
                     &lt;span class=&quot;o&quot;&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;delay&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ms&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;ms.&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
  &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;from &lt;a href=&quot;https://source.chromium.org/chromium/chromium/src/+/main:third_party/webrtc/p2p/base/turn_port.cc;l=1846&quot; target=&quot;_blank&quot;&gt;https://source.chromium.org/chromium/chromium/src/+/main:third_party/webrtc/p2p/base/turn_port.cc;l=1846&lt;/a&gt;&lt;/p&gt;

&lt;h2 id=&quot;22-indication&quot;&gt;2.2 indication&lt;/h2&gt;
&lt;p&gt;端上传输数据发送至服务器的信令叫 send indication, 服务端发向端上叫 data indication。（感觉这个命名不太对应）&lt;/p&gt;

&lt;p&gt;send indication的头部overhead相对channel的较大，有36B，其中指定了peer地址，也就是要发向谁。服务器会根据peer地址查找permission是否存在，存在的话则取出承载的数据发向peer。&lt;/p&gt;

&lt;p style=&quot;text-align: center&quot;&gt;
&lt;img src=&quot;../assets/pic/turn/2.2.webp&quot; width=&quot;800&quot; /&gt;
&lt;br /&gt;
send indication 抓包
&lt;/p&gt;

&lt;p&gt;收到peer的包时检查channel方式是否建立了，如果建立了优先用channel方式，没有建立则用permission方式发回给端上，data indication结构和send indication相同。&lt;/p&gt;

&lt;p&gt;看完上面这种传输方式，觉得有什么问题吗？&lt;/p&gt;

&lt;p&gt;注意到create permission时peer地址可以由客户端任意指定，如果服务部署在内网，用户可能恶意扫描内网服务器，类似 SSRF (Server-side request forgery) 漏洞，见这个报告 &lt;a href=&quot;https://hackerone.com/reports/333419?from_wecom=1&quot; target=&quot;_blank&quot;&gt;https://hackerone.com/reports/333419?from_wecom=1&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;The attacker may proxy TCP connections to the internal network by setting the  &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;XOR-PEER-ADDRESS&lt;/code&gt;  of the TURN connect message (method  &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0x000A&lt;/code&gt; , &lt;a href=&quot;https://tools.ietf.org/html/rfc6062#section-4.3&quot; target=&quot;_blank&quot;&gt;https://tools.ietf.org/html/rfc6062#section-4.3&lt;/a&gt; ) to a private IPv4 address.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;UDP packets may be proxied by setting the  &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;XOR-PEER-ADDRESS&lt;/code&gt;  to a private IP in the TURN send message indication (method  &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0x0006&lt;/code&gt; , &lt;a href=&quot;https://tools.ietf.org/html/rfc5766#section-10&quot; target=&quot;_blank&quot;&gt;https://tools.ietf.org/html/rfc5766#section-10&lt;/a&gt; ).&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;比如内网某台服务器部了HTTP服务给内网使用的，创建资源时端上指定TURN和peer之间是TCP方式（pion/turn不支持，coturn支持），后续创建permission和send indication时指定peer address是内网地址（暴力穷举），将HTTP请求包装在TURN协议中，这样就获取了内网服务器上的数据。&lt;/p&gt;

&lt;p&gt;下一节要介绍的传输方式也有这个问题，解决方法的话，如果只是为了WebRTC中转，WebRTC只用到UDP，可以禁掉TURN分配TCP relay端口功能，然后将常用协议的UDP端口也封禁，或者校验peer地址，可以详细看下原贴中作者说的。&lt;/p&gt;

&lt;h1 id=&quot;3-channel-方式传输数据&quot;&gt;3. channel 方式传输数据&lt;/h1&gt;

&lt;p style=&quot;text-align: center&quot;&gt;
&lt;img src=&quot;../assets/pic/turn/3channel.webp&quot; width=&quot;700&quot; /&gt;
&lt;br /&gt;
channel 方式概览 from RFC
&lt;/p&gt;

&lt;h2 id=&quot;31-channel-bind-request&quot;&gt;3.1 channel bind request&lt;/h2&gt;
&lt;p&gt;与permission方式类似，发数据前先请求创建通道，它在&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TurnEntry&lt;/code&gt;对象发送真实数据时请求创建，见下面的代码，关键字 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;SendChannelBindRequest&lt;/code&gt;。&lt;/p&gt;

&lt;div class=&quot;language-cpp highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;TurnEntry&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;::&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Send&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                    &lt;span class=&quot;kt&quot;&gt;size_t&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                    &lt;span class=&quot;kt&quot;&gt;bool&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;payload&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                    &lt;span class=&quot;k&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rtc&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;::&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;PacketOptions&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;amp;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;options&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;rtc&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;::&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ByteBufferWriter&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;buf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
  &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;state_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;STATE_BOUND&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;||&lt;/span&gt;
      &lt;span class=&quot;o&quot;&gt;!&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;port_&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;TurnCustomizerAllowChannelData&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;payload&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;// If we haven&apos;t bound the channel yet, we have to use a Send Indication.&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;// The turn_customizer_ can also make us use Send Indication.&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;TurnMessage&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;msg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;TURN_SEND_INDICATION&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;msg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;AddAttribute&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;::&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;make_unique&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;StunXorAddressAttribute&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;STUN_ATTR_XOR_PEER_ADDRESS&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ext_addr_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;));&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;msg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;AddAttribute&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;::&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;make_unique&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;StunByteStringAttribute&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;STUN_ATTR_DATA&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;));&lt;/span&gt;

    &lt;span class=&quot;n&quot;&gt;port_&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;TurnCustomizerMaybeModifyOutgoingStunMessage&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;amp;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;msg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;bool&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;success&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;msg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Write&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;amp;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;buf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;RTC_DCHECK&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;success&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;

    &lt;span class=&quot;c1&quot;&gt;// If we&apos;re sending real data, request a channel bind that we can use later.&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;state_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;STATE_UNBOUND&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;payload&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
      &lt;span class=&quot;n&quot;&gt;SendChannelBindRequest&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
      &lt;span class=&quot;n&quot;&gt;state_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;STATE_BINDING&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
  &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;// If the channel is bound, we can send the data as a Channel Message.&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;buf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;WriteUInt16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;channel_id_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;buf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;WriteUInt16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;static_cast&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;uint16_t&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;));&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;buf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;WriteBytes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;reinterpret_cast&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;char&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&amp;gt;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
  &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;rtc&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;::&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;PacketOptions&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;modified_options&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;options&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;modified_options&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;info_signaled_after_sent&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;turn_overhead_bytes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;
      &lt;span class=&quot;n&quot;&gt;buf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
  &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;port_&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Send&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;buf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;buf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;modified_options&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;from &lt;a href=&quot;https://source.chromium.org/chromium/chromium/src/+/main:third_party/webrtc/p2p/base/turn_port.cc;l=1846&quot; target=&quot;_blank&quot;&gt;https://source.chromium.org/chromium/chromium/src/+/main:third_party/webrtc/p2p/base/turn_port.cc;l=1846&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;创建请求中的有一个重要字段 channel number，由端上生成，标识了这个通道，通道号取值规定&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;0x0000-0x3FFF: 不能用来作为信道号&lt;/li&gt;
  &lt;li&gt;0x4000-0x7FFF: 可以作为信道号的值(16383个)&lt;/li&gt;
  &lt;li&gt;0x8000-0xFFFF: 保留值，留给以后使用&lt;/li&gt;
&lt;/ul&gt;

&lt;p style=&quot;text-align: center&quot;&gt;
&lt;img src=&quot;../assets/pic/turn/3.1bindreq.webp&quot; width=&quot;650&quot; /&gt;
&lt;br /&gt;
channel bind request 抓包
&lt;/p&gt;

&lt;p&gt;服务端收到创建请求后，在&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Allocation&lt;/code&gt;结构体的&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;channelBindings&lt;/code&gt;数组中增加一项，通道号或peer地址标识了这个channel，同时创建定时器，超时时间10分钟。如果channel已创建，则刷新expire。另外&lt;strong&gt;bind request都会刷新permission的expire&lt;/strong&gt;。最后回包给端上。&lt;/p&gt;

&lt;p&gt;端上收到回包后也是准备好下次心跳保活，这里有个小的优化，见下面代码的注释，因为channel bind方式发心跳会同时帮permission方式刷新心跳，permission的超时时间更短，所以用permission的超时时间减一分钟作为下次发心跳的间隔。&lt;/p&gt;

&lt;div class=&quot;language-cpp highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;TurnChannelBindRequest&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;::&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;OnResponse&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;StunMessage&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;response&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;RTC_LOG&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;LS_INFO&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;port_&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ToString&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
                   &lt;span class=&quot;o&quot;&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;: TURN channel bind requested successfully, id=&quot;&lt;/span&gt;
                   &lt;span class=&quot;o&quot;&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rtc&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;::&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hex_encode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;id&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
                   &lt;span class=&quot;o&quot;&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;, code=0&quot;&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;// Makes logging easier to parse.&lt;/span&gt;
                      &lt;span class=&quot;s&quot;&gt;&quot;, rtt=&quot;&lt;/span&gt;
                   &lt;span class=&quot;o&quot;&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Elapsed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;();&lt;/span&gt;

  &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;entry_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;entry_&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;OnChannelBindSuccess&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;();&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;// Refresh the channel binding just under the permission timeout&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;// threshold. The channel binding has a longer lifetime, but&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;// this is the easiest way to keep both the channel and the&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;// permission from expiring.&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;TimeDelta&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;delay&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kTurnPermissionTimeout&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;TimeDelta&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;::&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Minutes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;entry_&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;SendChannelBindRequest&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;delay&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ms&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;());&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;RTC_LOG&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;LS_INFO&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;port_&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ToString&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;: Scheduled channel bind in &quot;&lt;/span&gt;
                     &lt;span class=&quot;o&quot;&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;delay&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ms&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;ms.&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
  &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;from &lt;a href=&quot;https://source.chromium.org/chromium/chromium/src/+/main:third_party/webrtc/p2p/base/turn_port.cc;l=1732&quot; target=&quot;_blank&quot;&gt;https://source.chromium.org/chromium/chromium/src/+/main:third_party/webrtc/p2p/base/turn_port.cc;l=1732&lt;/a&gt;&lt;/p&gt;

&lt;h2 id=&quot;32-channel-data&quot;&gt;3.2 channel data&lt;/h2&gt;
&lt;p&gt;从上一节发送真实数据的代码&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TurnEntry::Send()&lt;/code&gt;中可以看到，发数据时如果channel方式已创建则用channel方式传输（即优先channel方式发送），它的overhead只有4B，比indication方式overhead少多了：&lt;/p&gt;

&lt;p style=&quot;text-align: center&quot;&gt;
&lt;img src=&quot;../assets/pic/turn/3.2channeldata.webp&quot; width=&quot;800&quot; /&gt;
&lt;br /&gt;
channel data 抓包
&lt;/p&gt;

&lt;p&gt;看完以上两种传输方式，我产生一个疑问，channel方式比permission方式overhead更少，而且发心跳时也可以刷新permission的expire，说白了功能更加强大，是否可以只用channel方式，在初始时（&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TurnEntry&lt;/code&gt;构造函数）用channel bind代替create permission呢？&lt;/p&gt;

&lt;p&gt;在 stackoverflow 上问了这个问题 &lt;a href=&quot;https://stackoverflow.com/questions/75611078/why-not-use-only-channel-data-in-webrtc-turn-client&quot; target=&quot;_blank&quot;&gt;https://stackoverflow.com/questions/75611078/why-not-use-only-channel-data-in-webrtc-turn-client&lt;/a&gt; ，在ICE RFC 5245文档中&lt;font color=&quot;red&quot;&gt;推荐&lt;/font&gt;ICE过程结束后再创建channel，也就是candidate pair选中后创建。其实TURN的文档里压根不关心携带的数据具体是什么，candidate 概念是WebRTC ICE的，ICE文档中推荐这么用，我认为native端可以优化改成只用channel方式。&lt;/p&gt;

&lt;p&gt;最后总结下，请求类的协议后台需要&lt;strong&gt;鉴权MAC码&lt;/strong&gt;，有allocation的分配和刷新请求、create permission请求、channel bind请求。TURN中涉及三种&lt;strong&gt;定时器&lt;/strong&gt;，对应文中三部分，端上需要定时发“心跳”保活，其中 permission 可以由 channel bind 保活。&lt;/p&gt;

&lt;p&gt;参考文献&lt;/p&gt;

&lt;p&gt;[1] TURN RFC 8656 (2020年) &lt;a href=&quot;https://datatracker.ietf.org/doc/html/rfc8656&quot; target=&quot;_blank&quot;&gt;https://datatracker.ietf.org/doc/html/rfc8656&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;[2] stun协议笔记二（webrtc之turn流程简介）by crystlhuang &lt;a href=&quot;https://blog.csdn.net/CrystalShaw/article/details/103505029&quot; target=&quot;_blank&quot;&gt;https://blog.csdn.net/CrystalShaw/article/details/103505029&lt;/a&gt;&lt;/p&gt;
</description>
        <pubDate>Mon, 06 Mar 2023 00:00:00 +0000</pubDate>
        <link>https://justme0.com//archive/turn.html</link>
        <guid isPermaLink="true">https://justme0.com//archive/turn.html</guid>
        
        
      </item>
    
  </channel>
</rss>
