425 const std::string source = isUrl(requested_path) ? requested_path : std::filesystem::absolute(requested_path).lexically_normal().string();
426 if (!isUrl(source) && !std::filesystem::is_regular_file(std::filesystem::path(source))) {
427 std::cerr <<
"acmxvk: audio file is not readable: " << source <<
'\n';
430 const std::size_t initial_sample_count =
samples.size();
432 AVFormatContext *format =
nullptr;
433 AVCodecContext *codec =
nullptr;
434 SwrContext *resampler =
nullptr;
435 AVPacket *packet =
nullptr;
436 AVFrame *frame =
nullptr;
438 auto release = [&]() {
439 av_frame_free(&frame);
440 av_packet_free(&packet);
441 swr_free(&resampler);
442 avcodec_free_context(&codec);
443 avformat_close_input(&format);
446 int result = avformat_open_input(&format, source.c_str(),
nullptr,
nullptr);
448 std::cerr <<
"acmxvk: could not open audio file: " << ffmpegError(result) <<
'\n';
452 result = avformat_find_stream_info(format,
nullptr);
454 std::cerr <<
"acmxvk: could not read audio stream information: " << ffmpegError(result) <<
'\n';
459 const AVCodec *decoder =
nullptr;
460 const int stream_index = av_find_best_stream(format, AVMEDIA_TYPE_AUDIO, -1, -1, &decoder, 0);
461 if (stream_index < 0 || decoder ==
nullptr) {
462 std::cerr <<
"acmxvk: media file contains no decodable audio stream\n";
467 codec = avcodec_alloc_context3(decoder);
468 if (codec ==
nullptr) {
469 std::cerr <<
"acmxvk: could not allocate the audio decoder\n";
473 result = avcodec_parameters_to_context(codec, format->streams[stream_index]->codecpar);
474 if (result < 0 || (result = avcodec_open2(codec, decoder,
nullptr)) < 0) {
475 std::cerr <<
"acmxvk: could not initialize the audio decoder: " << ffmpegError(result) <<
'\n';
479 if (codec->sample_rate <= 0 || codec->ch_layout.nb_channels == 0) {
480 std::cerr <<
"acmxvk: audio stream has an invalid sample format\n";
485 AVChannelLayout output_layout = AV_CHANNEL_LAYOUT_MONO;
486 result = swr_alloc_set_opts2(&resampler, &output_layout, AV_SAMPLE_FMT_FLT,
static_cast<int>(FILE_SAMPLE_RATE), &codec->ch_layout, codec->sample_fmt, codec->sample_rate, 0,
nullptr);
487 av_channel_layout_uninit(&output_layout);
488 if (result < 0 || resampler ==
nullptr || (result = swr_init(resampler)) < 0) {
489 std::cerr <<
"acmxvk: could not initialize audio resampling: " << ffmpegError(result) <<
'\n';
494 packet = av_packet_alloc();
495 frame = av_frame_alloc();
496 if (packet ==
nullptr || frame ==
nullptr) {
497 std::cerr <<
"acmxvk: could not allocate FFmpeg audio frames\n";
502 auto append_frame = [&]() ->
bool {
503 const int capacity =
static_cast<int>(av_rescale_rnd(swr_get_delay(resampler, codec->sample_rate) + frame->nb_samples, FILE_SAMPLE_RATE, codec->sample_rate, AV_ROUND_UP));
507 std::vector<float> converted(
static_cast<std::size_t
>(capacity));
508 std::uint8_t *
output[] = {
reinterpret_cast<std::uint8_t *
>(converted.data())};
509 const int count = swr_convert(resampler,
output, capacity,
const_cast<const std::uint8_t **
>(frame->extended_data), frame->nb_samples);
511 std::cerr <<
"acmxvk: audio resampling failed: " << ffmpegError(count) <<
'\n';
514 samples.insert(
samples.end(), converted.begin(), converted.begin() + count);
518 auto drain_decoder = [&]() ->
bool {
520 const int receive = avcodec_receive_frame(codec, frame);
521 if (receive == AVERROR(EAGAIN) || receive == AVERROR_EOF) {
525 std::cerr <<
"acmxvk: audio decoding failed: " << ffmpegError(receive) <<
'\n';
528 if (!append_frame()) {
531 av_frame_unref(frame);
536 while ((result = av_read_frame(format, packet)) >= 0) {
537 if (packet->stream_index == stream_index) {
538 result = avcodec_send_packet(codec, packet);
539 if (result < 0 || !drain_decoder()) {
541 std::cerr <<
"acmxvk: could not submit audio packet: " << ffmpegError(result) <<
'\n';
546 av_packet_unref(packet);
552 result = avcodec_send_packet(codec,
nullptr);
553 decoded = (result >= 0 || result == AVERROR_EOF) && drain_decoder();
557 const int capacity =
static_cast<int>(av_rescale_rnd(swr_get_delay(resampler, codec->sample_rate), FILE_SAMPLE_RATE, codec->sample_rate, AV_ROUND_UP));
561 std::vector<float> converted(
static_cast<std::size_t
>(capacity));
562 std::uint8_t *
output[] = {
reinterpret_cast<std::uint8_t *
>(converted.data())};
563 const int count = swr_convert(resampler,
output, capacity,
nullptr, 0);
565 decoded = count == 0;
568 samples.insert(
samples.end(), converted.begin(), converted.begin() + count);
572 const std::size_t decoded_sample_count =
samples.size() - initial_sample_count;
573 if (!decoded || decoded_sample_count == 0) {
574 samples.resize(initial_sample_count);
575 std::cerr <<
"acmxvk: audio file produced no usable samples: " << source <<
'\n';
579 std::cout <<
"acmxvk: decoded audio track " << source <<
" (" <<
static_cast<double>(decoded_sample_count) /
static_cast<double>(FILE_SAMPLE_RATE) <<
" seconds, " << decoded_sample_count <<
" mono samples at " << FILE_SAMPLE_RATE <<
" Hz)\n";
631 bool mux_into_video(
const std::string &requested_video_path,
double video_duration) {
633 if (
samples.empty() || !std::isfinite(video_duration) || video_duration <= 0.0) {
634 std::cerr <<
"acmxvk: cannot mux " << (
live_recording_source ?
"live audio input" :
"file audio") <<
" without samples and a positive video duration\n";
638 const std::filesystem::path video_path = std::filesystem::absolute(requested_video_path).lexically_normal();
639 if (!std::filesystem::is_regular_file(video_path)) {
640 std::cerr <<
"acmxvk: encoded video is not readable for audio mux: " << video_path.string() <<
'\n';
645 const double mux_duration =
repeat ? video_duration : std::min(video_duration, source_duration);
646 const std::int64_t target_sample_count =
static_cast<std::int64_t
>(std::floor(mux_duration *
static_cast<double>(FILE_SAMPLE_RATE)));
647 if (target_sample_count <= 0) {
648 std::cerr <<
"acmxvk: file audio mux duration is empty\n";
652 const auto unique_value = std::chrono::steady_clock::now().time_since_epoch().count();
653 const std::filesystem::path temporary_path = video_path.parent_path() / (video_path.stem().
string() +
".acmxvk-mux-" + std::to_string(unique_value) + video_path.extension().string());
654 const std::string video_url = ffmpegPath(video_path);
655 const std::string temporary_url = ffmpegPath(temporary_path);
657 AVFormatContext *input_context =
nullptr;
658 AVFormatContext *output_context =
nullptr;
659 AVCodecContext *audio_encoder =
nullptr;
660 SwrContext *resampler =
nullptr;
661 AVFrame *audio_frame =
nullptr;
662 AVPacket *input_packet =
nullptr;
663 AVPacket *audio_packet =
nullptr;
665 auto cleanup = [&]() {
666 av_packet_free(&audio_packet);
667 av_packet_free(&input_packet);
668 av_frame_free(&audio_frame);
669 swr_free(&resampler);
670 avcodec_free_context(&audio_encoder);
671 avformat_close_input(&input_context);
672 if (output_context !=
nullptr) {
673 if ((output_context->oformat->flags & AVFMT_NOFILE) == 0) {
674 avio_closep(&output_context->pb);
676 avformat_free_context(output_context);
677 output_context =
nullptr;
681 auto fail = [&](std::string_view message,
int error) {
682 std::cerr <<
"acmxvk: " << message;
684 std::cerr <<
": " << ffmpegError(error);
688 std::error_code remove_error;
689 std::filesystem::remove(temporary_path, remove_error);
693 int result = avformat_open_input(&input_context, video_url.c_str(),
nullptr,
nullptr);
695 return fail(
"could not open encoded video for audio mux", result);
697 result = avformat_find_stream_info(input_context,
nullptr);
699 return fail(
"could not read encoded video stream information", result);
701 const int input_video_index = av_find_best_stream(input_context, AVMEDIA_TYPE_VIDEO, -1, -1,
nullptr, 0);
702 if (input_video_index < 0) {
703 return fail(
"encoded output contains no video stream", input_video_index);
706 result = avformat_alloc_output_context2(&output_context,
nullptr,
nullptr, temporary_url.c_str());
707 if (result < 0 || output_context ==
nullptr) {
708 return fail(
"could not create audio-mux output container", result);
711 AVStream *input_video = input_context->streams[input_video_index];
712 AVStream *output_video = avformat_new_stream(output_context,
nullptr);
713 if (output_video ==
nullptr) {
714 return fail(
"could not create remuxed video stream", AVERROR(ENOMEM));
716 result = avcodec_parameters_copy(output_video->codecpar, input_video->codecpar);
718 return fail(
"could not copy encoded video parameters", result);
720 output_video->codecpar->codec_tag = 0;
721 output_video->time_base = input_video->time_base;
722 output_video->avg_frame_rate = input_video->avg_frame_rate;
724 const AVCodec *aac_encoder = avcodec_find_encoder(AV_CODEC_ID_AAC);
725 if (aac_encoder ==
nullptr) {
726 return fail(
"linked FFmpeg has no AAC encoder", AVERROR_ENCODER_NOT_FOUND);
728 AVStream *output_audio = avformat_new_stream(output_context, aac_encoder);
729 if (output_audio ==
nullptr) {
730 return fail(
"could not create encoded audio stream", AVERROR(ENOMEM));
732 audio_encoder = avcodec_alloc_context3(aac_encoder);
733 if (audio_encoder ==
nullptr) {
734 return fail(
"could not allocate AAC encoder", AVERROR(ENOMEM));
736 audio_encoder->bit_rate = 192000;
737 audio_encoder->sample_fmt = AV_SAMPLE_FMT_FLTP;
738 audio_encoder->sample_rate =
static_cast<int>(FILE_SAMPLE_RATE);
739 audio_encoder->time_base = AVRational{1,
static_cast<int>(FILE_SAMPLE_RATE)};
740 av_channel_layout_default(&audio_encoder->ch_layout, 1);
741 if ((output_context->oformat->flags & AVFMT_GLOBALHEADER) != 0) {
742 audio_encoder->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
744 result = avcodec_open2(audio_encoder, aac_encoder,
nullptr);
746 return fail(
"could not initialize AAC encoder", result);
748 result = avcodec_parameters_from_context(output_audio->codecpar, audio_encoder);
750 return fail(
"could not export AAC stream parameters", result);
752 output_audio->codecpar->codec_tag = 0;
753 output_audio->time_base = audio_encoder->time_base;
755 AVChannelLayout input_layout = AV_CHANNEL_LAYOUT_MONO;
756 result = swr_alloc_set_opts2(&resampler, &audio_encoder->ch_layout, audio_encoder->sample_fmt, audio_encoder->sample_rate, &input_layout, AV_SAMPLE_FMT_FLT,
static_cast<int>(FILE_SAMPLE_RATE), 0,
nullptr);
757 av_channel_layout_uninit(&input_layout);
758 if (result < 0 || resampler ==
nullptr || (result = swr_init(resampler)) < 0) {
759 return fail(
"could not initialize audio mux resampler", result);
762 const int audio_frame_capacity = audio_encoder->frame_size > 0 ? audio_encoder->frame_size : 1024;
763 audio_frame = av_frame_alloc();
764 input_packet = av_packet_alloc();
765 audio_packet = av_packet_alloc();
766 if (audio_frame ==
nullptr || input_packet ==
nullptr || audio_packet ==
nullptr) {
767 return fail(
"could not allocate audio mux frames", AVERROR(ENOMEM));
769 audio_frame->format = audio_encoder->sample_fmt;
770 audio_frame->sample_rate = audio_encoder->sample_rate;
771 audio_frame->nb_samples = audio_frame_capacity;
772 result = av_channel_layout_copy(&audio_frame->ch_layout, &audio_encoder->ch_layout);
773 if (result < 0 || (result = av_frame_get_buffer(audio_frame, 0)) < 0) {
774 return fail(
"could not allocate AAC sample buffer", result);
777 if ((output_context->oformat->flags & AVFMT_NOFILE) == 0) {
778 result = avio_open(&output_context->pb, temporary_url.c_str(), AVIO_FLAG_WRITE);
780 return fail(
"could not open temporary mux output", result);
783 result = avformat_write_header(output_context,
nullptr);
785 return fail(
"could not write audio-mux container header", result);
788 std::int64_t source_position = 0;
789 std::int64_t encoded_position = 0;
790 std::vector<float> input_samples(
static_cast<std::size_t
>(audio_frame_capacity));
792 auto drain_audio_packets = [&]() {
794 const int receive = avcodec_receive_packet(audio_encoder, audio_packet);
795 if (receive == AVERROR(EAGAIN) || receive == AVERROR_EOF) {
802 audio_packet->stream_index = output_audio->index;
803 av_packet_rescale_ts(audio_packet, audio_encoder->time_base, output_audio->time_base);
804 const int write = av_interleaved_write_frame(output_context, audio_packet);
805 av_packet_unref(audio_packet);
813 auto encode_audio_frame = [&]() {
814 const std::int64_t remaining = target_sample_count - source_position;
815 if (remaining <= 0) {
818 const int source_count =
static_cast<int>(std::min<std::int64_t>(remaining, audio_frame_capacity));
819 int submitted_count = source_count;
820 if (source_count < audio_frame_capacity && (aac_encoder->capabilities & AV_CODEC_CAP_SMALL_LAST_FRAME) == 0) {
821 submitted_count = audio_frame_capacity;
823 for (
int index = 0; index < submitted_count; ++index) {
824 if (index >= source_count) {
825 input_samples[
static_cast<std::size_t
>(index)] = 0.0F;
828 const std::size_t sample_index =
repeat ?
static_cast<std::size_t
>(source_position + index) %
samples.size() :
static_cast<std::size_t
>(source_position + index);
829 input_samples[
static_cast<std::size_t
>(index)] =
samples[sample_index];
832 audio_frame->nb_samples = submitted_count;
833 result = av_frame_make_writable(audio_frame);
837 const std::uint8_t *input_data[] = {
reinterpret_cast<const std::uint8_t *
>(input_samples.data())};
838 const int converted = swr_convert(resampler, audio_frame->data, submitted_count, input_data, submitted_count);
843 audio_frame->nb_samples = converted;
844 audio_frame->pts = encoded_position;
845 result = avcodec_send_frame(audio_encoder, audio_frame);
846 if (result < 0 || !drain_audio_packets()) {
849 source_position += source_count;
850 encoded_position += converted;
854 bool video_complete =
false;
855 while ((result = av_read_frame(input_context, input_packet)) >= 0) {
856 if (input_packet->stream_index != input_video_index) {
857 av_packet_unref(input_packet);
860 const std::int64_t timestamp = input_packet->pts != AV_NOPTS_VALUE ? input_packet->pts : input_packet->dts;
861 const double packet_time = timestamp == AV_NOPTS_VALUE ? 0.0 :
static_cast<double>(timestamp) * av_q2d(input_video->time_base);
862 if (timestamp != AV_NOPTS_VALUE && packet_time > mux_duration) {
863 av_packet_unref(input_packet);
864 video_complete =
true;
868 const std::int64_t audio_target = std::min<std::int64_t>(target_sample_count,
static_cast<std::int64_t
>(std::ceil((packet_time +
static_cast<double>(audio_frame_capacity) /
static_cast<double>(FILE_SAMPLE_RATE)) *
static_cast<double>(FILE_SAMPLE_RATE))));
869 while (source_position < audio_target) {
870 if (!encode_audio_frame()) {
871 return fail(
"could not encode AAC samples", result);
875 av_packet_rescale_ts(input_packet, input_video->time_base, output_video->time_base);
876 input_packet->stream_index = output_video->index;
877 input_packet->pos = -1;
878 result = av_interleaved_write_frame(output_context, input_packet);
879 av_packet_unref(input_packet);
881 return fail(
"could not remux encoded video packet", result);
884 if (!video_complete && result != AVERROR_EOF) {
885 return fail(
"could not finish reading encoded video", result);
888 while (source_position < target_sample_count) {
889 if (!encode_audio_frame()) {
890 return fail(
"could not finish AAC encoding", result);
893 result = avcodec_send_frame(audio_encoder,
nullptr);
894 if (result < 0 || !drain_audio_packets()) {
895 return fail(
"could not flush AAC encoder", result);
897 result = av_write_trailer(output_context);
899 return fail(
"could not finalize audio-mux container", result);
901 if ((output_context->oformat->flags & AVFMT_NOFILE) == 0) {
902 result = avio_closep(&output_context->pb);
904 return fail(
"could not flush temporary mux output", result);
909 std::error_code replace_error;
910 if (!replaceFile(temporary_path, video_path, replace_error)) {
911 std::cerr <<
"acmxvk: could not atomically replace encoded video "
912 "with muxed output: "
913 << replace_error.message() <<
'\n';
914 std::error_code remove_error;
915 std::filesystem::remove(temporary_path, remove_error);
919 std::cout <<
"acmxvk: muxed " << (
live_recording_source ?
"live audio input" : (
track_paths.size() > 1 ?
"audio playlist" :
"audio file")) <<
" into " << video_path.string() <<
" (" << mux_duration <<
" seconds" << (
repeat ?
", repeated" :
"") <<
")\n";