// مرمّز AAC-LC للموقع (بديل لما المتصفح ما فيه AudioEncoder يرمّز AAC، مثل Safari قبل 26). // مبني على مرمّز AAC الأصلي في FFmpeg (libavcodec، رخصة LGPL 2.1 أو أحدث). الملف هذا وسكربت البناء منشورين، // والمرمّز ملف wasm منفصل يتحمّل وقت الحاجة، فأي أحد يقدر يبدّله بنسخة مبنية بنفسه (شروط LGPL). // الواجهة: aac_open ← aac_input (عنوان مخزن الإدخال) ← aac_send ← aac_receive (لين يرجع 0) ← ... ← aac_send(0) للإنهاء. #include #include #include #include #include static AVCodecContext *ctx; static AVFrame *frame; static AVPacket *pkt; static int64_t next_pts; EMSCRIPTEN_KEEPALIVE int aac_open(int sample_rate, int channels, int bitrate) { const AVCodec *c = avcodec_find_encoder(AV_CODEC_ID_AAC); if (!c) return -1; ctx = avcodec_alloc_context3(c); ctx->sample_rate = sample_rate; ctx->sample_fmt = AV_SAMPLE_FMT_FLTP; av_channel_layout_default(&ctx->ch_layout, channels); ctx->bit_rate = bitrate; ctx->profile = AV_PROFILE_AAC_LOW; ctx->time_base = (AVRational){1, sample_rate}; ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; // نبي AudioSpecificConfig للـ esds int r = avcodec_open2(ctx, c, NULL); if (r < 0) return r; frame = av_frame_alloc(); frame->nb_samples = ctx->frame_size; frame->format = ctx->sample_fmt; av_channel_layout_copy(&frame->ch_layout, &ctx->ch_layout); frame->sample_rate = sample_rate; if ((r = av_frame_get_buffer(frame, 0)) < 0) return r; pkt = av_packet_alloc(); next_pts = 0; return ctx->frame_size; // 1024 } EMSCRIPTEN_KEEPALIVE uint8_t *aac_extradata(void) { return ctx->extradata; } EMSCRIPTEN_KEEPALIVE int aac_extradata_size(void) { return ctx->extradata_size; } /** مخزن القناة ch (float، frame_size عينة). يتعبّى من JS قبل aac_send */ EMSCRIPTEN_KEEPALIVE float *aac_input(int ch) { av_frame_make_writable(frame); return (float *)frame->data[ch]; } /** nb = عدد العينات في المخزن (≤ frame_size)، و 0 = نهاية الصوت (يطلع الباقي) */ EMSCRIPTEN_KEEPALIVE int aac_send(int nb) { if (nb <= 0) return avcodec_send_frame(ctx, NULL); if (nb < ctx->frame_size) for (int ch = 0; ch < ctx->ch_layout.nb_channels; ch++) memset((float *)frame->data[ch] + nb, 0, (ctx->frame_size - nb) * sizeof(float)); frame->nb_samples = nb; frame->pts = next_pts; next_pts += nb; return avcodec_send_frame(ctx, frame); } /** حجم الحزمة الجاية (>0)، أو 0 = يبي إدخال أكثر أو خلص، أو سالب = خطأ */ EMSCRIPTEN_KEEPALIVE int aac_receive(void) { av_packet_unref(pkt); int r = avcodec_receive_packet(ctx, pkt); if (r == AVERROR(EAGAIN) || r == AVERROR_EOF) return 0; return r < 0 ? r : pkt->size; } EMSCRIPTEN_KEEPALIVE uint8_t *aac_packet(void) { return pkt->data; } /** وقت الحزمة بالعينات (بعد إزاحة البداية حق المرمّز) */ EMSCRIPTEN_KEEPALIVE double aac_packet_pts(void) { return (double)pkt->pts; } EMSCRIPTEN_KEEPALIVE int aac_packet_duration(void) { return (int)pkt->duration; } EMSCRIPTEN_KEEPALIVE int aac_initial_padding(void) { return ctx->initial_padding; } EMSCRIPTEN_KEEPALIVE void aac_close(void) { av_packet_free(&pkt); av_frame_free(&frame); avcodec_free_context(&ctx); }