BlueGit

ict rusty-teams

Files

rusty-teams / vendor / webrtc-sys / build.rs

build.rs

build.rs 27.4 KiB Download Raw
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::path::Path;
16use std::path::PathBuf;
17use std::{env, path, process::Command};
18
19fn main() {
20 if env::var("DOCS_RS").is_ok() {
21 return;
22 }
23
24 let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap();
25 let target_arch = env::var("CARGO_CFG_TARGET_ARCH").unwrap();
26 let is_desktop = target_os == "linux" || target_os == "windows" || target_os == "macos";
27
28 println!("cargo:rerun-if-env-changed=LK_DEBUG_WEBRTC");
29 println!("cargo:rerun-if-env-changed=LK_CUSTOM_WEBRTC");
30
31 let mut rust_files = vec![
32 "src/peer_connection.rs",
33 "src/peer_connection_factory.rs",
34 "src/audio_device_controller.rs",
35 "src/media_stream.rs",
36 "src/media_stream_track.rs",
37 "src/audio_track.rs",
38 "src/video_track.rs",
39 "src/data_channel.rs",
40 "src/frame_cryptor.rs",
41 "src/jsep.rs",
42 "src/candidate.rs",
43 "src/rtp_parameters.rs",
44 "src/rtp_sender.rs",
45 "src/rtp_receiver.rs",
46 "src/rtp_transceiver.rs",
47 "src/rtc_error.rs",
48 "src/webrtc.rs",
49 "src/video_frame.rs",
50 "src/video_frame_buffer.rs",
51 "src/helper.rs",
52 "src/yuv_helper.rs",
53 "src/audio_resampler.rs",
54 "src/android.rs",
55 "src/prohibit_libsrtp_initialization.rs",
56 "src/apm.rs",
57 "src/noise_hook.rs",
58 "src/audio_mixer.rs",
59 "src/packet_trailer.rs",
60 ];
61
62 if is_desktop {
63 rust_files.push("src/desktop_capturer.rs");
64 }
65
66 let mut builder = cxx_build::bridges(rust_files);
67
68 builder.files(&[
69 "src/peer_connection.cpp",
70 "src/peer_connection_factory.cpp",
71 "src/audio_device_controller.cpp",
72 "src/media_stream.cpp",
73 "src/media_stream_track.cpp",
74 "src/audio_track.cpp",
75 "src/video_track.cpp",
76 "src/data_channel.cpp",
77 "src/jsep.cpp",
78 "src/candidate.cpp",
79 "src/rtp_receiver.cpp",
80 "src/rtp_sender.cpp",
81 "src/rtp_transceiver.cpp",
82 "src/rtp_parameters.cpp",
83 "src/rtc_error.cpp",
84 "src/webrtc.cpp",
85 "src/video_frame.cpp",
86 "src/video_frame_buffer.cpp",
87 "src/dmabuf_video_frame_buffer.cpp",
88 "src/encoded_video_frame_buffer.cpp",
89 "src/video_encoder_factory.cpp",
90 "src/passthrough_video_encoder.cpp",
91 "src/video_decoder_factory.cpp",
92 "src/synthetic_audio_device.cpp",
93 "src/adm_proxy.cpp",
94 "src/audio_resampler.cpp",
95 "src/frame_cryptor.cpp",
96 "src/global_task_queue.cpp",
97 "src/prohibit_libsrtp_initialization.cpp",
98 "src/apm.cpp",
99 "src/noise_hook.cpp",
100 "src/audio_mixer.cpp",
101 "src/av1_bitstream.cpp",
102 "src/packet_trailer.cpp",
103 "src/packet_trailer_av1.cpp",
104 ]);
105
106 if is_desktop {
107 builder.file("src/desktop_capturer.cpp");
108 }
109
110 let webrtc_dir = webrtc_sys_build::webrtc_dir();
111 let webrtc_include = webrtc_dir.join("include");
112 let webrtc_lib = webrtc_dir.join("lib");
113
114 if !webrtc_dir.exists() {
115 webrtc_sys_build::download_webrtc().unwrap();
116 }
117
118 builder.includes(&[
119 path::PathBuf::from("./include"),
120 webrtc_include.clone(),
121 webrtc_include.join("third_party/abseil-cpp/"),
122 webrtc_include.join("third_party/libyuv/include/"),
123 webrtc_include.join("third_party/libc++/"),
124 // For mac & ios
125 webrtc_include.join("sdk/objc"),
126 webrtc_include.join("sdk/objc/base"),
127 ]);
128 builder.define("WEBRTC_APM_DEBUG_DUMP", "0");
129
130 println!("cargo:rustc-link-search=native={}", webrtc_lib.to_str().unwrap());
131
132 for (key, value) in webrtc_sys_build::webrtc_defines() {
133 let value = value.as_deref();
134 builder.define(key.as_str(), value);
135 }
136
137 // Link webrtc library
138 println!("cargo:rustc-link-lib=static=webrtc");
139 match target_os.as_str() {
140 "windows" => {
141 println!("cargo:rustc-link-lib=dylib=msdmo");
142 println!("cargo:rustc-link-lib=dylib=wmcodecdspuuid");
143 println!("cargo:rustc-link-lib=dylib=dmoguids");
144 println!("cargo:rustc-link-lib=dylib=crypt32");
145 println!("cargo:rustc-link-lib=dylib=iphlpapi");
146 println!("cargo:rustc-link-lib=dylib=ole32");
147 println!("cargo:rustc-link-lib=dylib=secur32");
148 println!("cargo:rustc-link-lib=dylib=winmm");
149 println!("cargo:rustc-link-lib=dylib=ws2_32");
150 println!("cargo:rustc-link-lib=dylib=strmiids");
151 println!("cargo:rustc-link-lib=dylib=d3d11");
152 println!("cargo:rustc-link-lib=dylib=gdi32");
153 println!("cargo:rustc-link-lib=dylib=dxgi");
154 println!("cargo:rustc-link-lib=dylib=dwmapi");
155 println!("cargo:rustc-link-lib=dylib=shcore");
156
157 //let path = env::current_dir().unwrap();
158 //println!("cargo:rustc-link-search=native={}/vaapi-windows/x64/lib", path.display());
159 //println!("cargo:rustc-link-lib=dylib=va");
160 //println!("cargo:rustc-link-lib=dylib=va_win32");
161
162 builder
163 //.include("./vaapi-windows/DirectX-Headers-1.0/include")
164 //.include(path::PathBuf::from("./vaapi-windows/x64/include"))
165 //.file("vaapi-windows/DirectX-Headers-1.0/src/dxguids.cpp")
166 //.file("src/vaapi/vaapi_display_win32.cpp")
167 //.file("src/vaapi/vaapi_h264_encoder_wrapper.cpp")
168 //.file("src/vaapi/vaapi_encoder_factory.cpp")
169 //.file("src/vaapi/h264_encoder_impl.cpp")
170 .flag("/std:c++20")
171 //.flag("/wd4819")
172 //.flag("/wd4068")
173 .flag("/EHsc");
174 }
175 "linux" => {
176 println!("cargo:rustc-link-lib=dylib=rt");
177 println!("cargo:rustc-link-lib=dylib=dl");
178 println!("cargo:rustc-link-lib=dylib=pthread");
179 println!("cargo:rustc-link-lib=dylib=m");
180
181 configure_hermetic_libcxx(&mut builder, &webrtc_include);
182
183 // In order to avoid any ABI mismatches we use the sysroot's headers.
184 add_gio_headers(&mut builder);
185
186 // Do not use pkg_config::probe_library, because we only require headers.
187 for lib_name in ["glib-2.0", "gobject-2.0", "gio-2.0"] {
188 let lib = pkg_config::Config::new().cargo_metadata(false).probe(lib_name).unwrap();
189 for path in lib.include_paths {
190 builder.include(path);
191 }
192 }
193
194 add_lazy_load_so(
195 &mut builder,
196 "desktop_capturer",
197 ["drm", "gbm", "X11", "Xfixes", "Xdamage", "Xrandr", "Xcomposite", "Xext"]
198 .map(String::from)
199 .to_vec(),
200 );
201
202 let x86 = target_arch == "x86_64" || target_arch == "i686";
203 let arm = target_arch == "aarch64" || target_arch.contains("arm");
204
205 if x86 {
206 if let Some(libva_include) = pkg_config::get_variable("libva", "includedir").ok() {
207 // Do not use pkg_config::probe_library because libva is dlopened
208 // and pkg_config::probe_library would link it.
209 builder
210 .include(libva_include)
211 .file("src/vaapi/vaapi_display_drm.cpp")
212 .file("src/vaapi/vaapi_h264_encoder_wrapper.cpp")
213 .file("src/vaapi/vaapi_encoder_factory.cpp")
214 .file("src/vaapi/h264_encoder_impl.cpp")
215 .flag("-DUSE_VAAPI_VIDEO_CODEC=1");
216
217 add_lazy_load_so(
218 &mut builder,
219 "vaapi",
220 ["va", "va-drm"].map(String::from).to_vec(),
221 );
222 } else {
223 println!("cargo:warning=libva not found; building without hardware accelerated video codecs");
224 }
225 }
226
227 if arm {
228 println!("cargo:rerun-if-env-changed=LK_JETSON_MMAPI_DIR");
229 let jetson_mmapi_dir = PathBuf::from(match env::var("LK_JETSON_MMAPI_DIR") {
230 Ok(p) => p,
231 Err(_) => "/usr/src/jetson_multimedia_api".to_owned(),
232 });
233 let jetson_mmapi_include = jetson_mmapi_dir.join("include");
234 if jetson_mmapi_include.exists() {
235 let jetson_classes_dir = jetson_mmapi_dir.join("samples/common/classes");
236
237 builder
238 .include(&jetson_mmapi_include)
239 .include("src/jetson")
240 .file("src/jetson/jetson_mmapi_encoder.cpp")
241 .file("src/jetson/jetson_plane_layout.cpp")
242 .file("src/jetson/jetson_runtime_loader.cpp")
243 .file("src/jetson/h264_encoder_impl.cpp")
244 .file("src/jetson/h265_encoder_impl.cpp")
245 .file("src/jetson/av1_encoder_impl.cpp")
246 .file("src/jetson/jetson_encoder_factory.cpp")
247 .flag("-DUSE_JETSON_VIDEO_CODEC=1");
248
249 let mmapi_sources = [
250 "NvElement.cpp",
251 "NvV4l2Element.cpp",
252 "NvV4l2ElementPlane.cpp",
253 "NvVideoEncoder.cpp",
254 "NvBuffer.cpp",
255 "NvLogging.cpp",
256 "NvElementProfiler.cpp",
257 ];
258 for src in &mmapi_sources {
259 let src_path = jetson_classes_dir.join(src);
260 if src_path.exists() {
261 builder.file(&src_path);
262 } else {
263 println!(
264 "cargo:warning=Jetson MMAPI source not found: {}",
265 src_path.display()
266 );
267 }
268 }
269
270 // libv4l2/libnvv4l2 and libnvbufsurface are dlopened at
271 // runtime (see src/jetson/jetson_runtime_loader.cpp), so
272 // the same aarch64 binary loads on non-Jetson systems
273 // where those libraries are absent.
274 add_lazy_load_so(
275 &mut builder,
276 "jetson",
277 ["v4l2", "nvbufsurface"].map(String::from).to_vec(),
278 );
279 }
280 }
281
282 if x86 || arm {
283 let cuda_home = PathBuf::from(match env::var("CUDA_HOME") {
284 Ok(p) => p,
285 Err(_) => "/usr/local/cuda".to_owned(),
286 });
287 let cuda_include_dir = cuda_home.join("include");
288
289 // libcuda and libnvcuvid are dlopened, so do not link them.
290 if cuda_include_dir.join("cuda.h").exists() {
291 builder
292 .include(cuda_include_dir)
293 .flag("-Isrc/nvidia/NvCodec/include")
294 .flag("-Isrc/nvidia/NvCodec/NvCodec")
295 .file("src/nvidia/NvCodec/NvCodec/NvDecoder/NvDecoder.cpp")
296 .file("src/nvidia/NvCodec/NvCodec/NvEncoder/NvEncoder.cpp")
297 .file("src/nvidia/NvCodec/NvCodec/NvEncoder/NvEncoderCuda.cpp")
298 .file("src/nvidia/h264_encoder_impl.cpp")
299 .file("src/nvidia/h265_encoder_impl.cpp")
300 .file("src/nvidia/av1_encoder_impl.cpp")
301 .file("src/nvidia/h264_decoder_impl.cpp")
302 .file("src/nvidia/h265_decoder_impl.cpp")
303 .file("src/nvidia/nvidia_decoder_factory.cpp")
304 .file("src/nvidia/nvidia_encoder_factory.cpp")
305 .file("src/nvidia/cuda_context.cpp")
306 .flag("-Wno-deprecated-declarations")
307 .flag("-DUSE_NVIDIA_VIDEO_CODEC=1");
308
309 add_lazy_load_so(
310 &mut builder,
311 "nvidia",
312 ["cuda", "nvcuvid"].map(String::from).to_vec(),
313 );
314 } else {
315 println!("cargo:warning=cuda.h not found; building without hardware accelerated video codec support for NVidia GPUs");
316 }
317 }
318
319 builder
320 .flag("-Wno-changes-meaning")
321 .flag("-Wno-deprecated-declarations")
322 .flag("-std=c++20");
323 }
324 "macos" => {
325 println!("cargo:rustc-link-lib=framework=Foundation");
326 println!("cargo:rustc-link-lib=framework=AVFoundation");
327 // rtc_base's platform certificate verifier calls SecTrust.
328 println!("cargo:rustc-link-lib=framework=Security");
329 println!("cargo:rustc-link-lib=framework=CoreAudio");
330 println!("cargo:rustc-link-lib=framework=AudioToolbox");
331 println!("cargo:rustc-link-lib=framework=AppKit");
332 println!("cargo:rustc-link-lib=framework=CoreMedia");
333 println!("cargo:rustc-link-lib=framework=CoreGraphics");
334 println!("cargo:rustc-link-lib=framework=VideoToolbox");
335 println!("cargo:rustc-link-lib=framework=CoreVideo");
336 println!("cargo:rustc-link-lib=framework=OpenGL");
337 println!("cargo:rustc-link-lib=framework=Metal");
338 println!("cargo:rustc-link-lib=framework=MetalKit");
339 println!("cargo:rustc-link-lib=framework=QuartzCore");
340 println!("cargo:rustc-link-lib=framework=IOKit");
341 println!("cargo:rustc-link-lib=framework=IOSurface");
342 println!("cargo:rustc-link-lib=framework=ScreenCaptureKit");
343
344 configure_darwin_sysroot(&mut builder);
345
346 builder
347 .file("src/objc_video_factory.mm")
348 .file("src/objc_video_frame_buffer.mm")
349 .flag("-stdlib=libc++")
350 .flag("-std=c++20")
351 .flag("-Wno-nullability-completeness");
352 }
353 "ios" => {
354 println!("cargo:rustc-link-lib=framework=Foundation");
355 println!("cargo:rustc-link-lib=framework=CoreFoundation");
356 println!("cargo:rustc-link-lib=framework=AVFoundation");
357 // rtc_base's platform certificate verifier calls SecTrust.
358 println!("cargo:rustc-link-lib=framework=Security");
359 println!("cargo:rustc-link-lib=framework=CoreAudio");
360 println!("cargo:rustc-link-lib=framework=UIKit");
361 println!("cargo:rustc-link-lib=framework=CoreVideo");
362 println!("cargo:rustc-link-lib=framework=CoreGraphics");
363 println!("cargo:rustc-link-lib=framework=CoreMedia");
364 println!("cargo:rustc-link-lib=framework=VideoToolbox");
365 println!("cargo:rustc-link-lib=framework=AudioToolbox");
366 println!("cargo:rustc-link-lib=framework=OpenGLES");
367 println!("cargo:rustc-link-lib=framework=GLKit");
368 println!("cargo:rustc-link-lib=framework=Metal");
369 println!("cargo:rustc-link-lib=framework=MetalKit");
370 println!("cargo:rustc-link-lib=framework=Network");
371 println!("cargo:rustc-link-lib=framework=QuartzCore");
372
373 configure_darwin_sysroot(&mut builder);
374
375 builder
376 .file("src/objc_video_factory.mm")
377 .file("src/objc_video_frame_buffer.mm")
378 .flag("-std=c++20");
379 }
380 "android" => {
381 webrtc_sys_build::configure_jni_symbols().unwrap();
382
383 println!("cargo:rustc-link-lib=EGL");
384 println!("cargo:rustc-link-lib=OpenSLES");
385 println!("cargo:rustc-link-lib=c++_static");
386 println!("cargo:rustc-link-lib=c++abi");
387
388 configure_android_sysroot(&mut builder);
389 builder
390 .file("src/android.cpp")
391 // Provides a weak stub for std::__ndk1::__hash_memory, which
392 // was removed from libc++_static.a exports in NDK r28.
393 .file("src/ndk_compat.cpp")
394 .flag("-std=c++20");
395 }
396 _ => {
397 panic!("Unsupported target, {}", target_os);
398 }
399 }
400
401 // TODO(theomonnom) Only add this define when building tests
402 builder.define("LIVEKIT_TEST", None);
403 builder.warnings(false).compile("webrtcsys-cxx");
404
405 for entry in glob::glob("./src/**/*.cpp").unwrap() {
406 println!("cargo:rerun-if-changed={}", entry.unwrap().display());
407 }
408
409 for entry in glob::glob("./src/**/*.mm").unwrap() {
410 println!("cargo:rerun-if-changed={}", entry.unwrap().display());
411 }
412
413 for entry in glob::glob("./include/**/*.h").unwrap() {
414 println!("cargo:rerun-if-changed={}", entry.unwrap().display());
415 }
416
417 if target_os.as_str() == "android" {
418 copy_libwebrtc_jar(&PathBuf::from(Path::new(&webrtc_dir)));
419 }
420}
421
422fn copy_libwebrtc_jar(webrtc_dir: &PathBuf) {
423 let jar_path = webrtc_dir.join("libwebrtc.jar");
424 let output_path = get_output_path();
425 let output_jar_path = output_path.join("libwebrtc.jar");
426 let res = std::fs::copy(jar_path, output_jar_path);
427 if let Err(e) = res {
428 println!("Failed to copy libwebrtc.jar: {}", e);
429 }
430}
431
432fn get_output_path() -> PathBuf {
433 let manifest_dir_string = env::var("CARGO_MANIFEST_DIR").unwrap();
434 let build_type = env::var("PROFILE").unwrap();
435 let build_target = env::var("TARGET").unwrap();
436 let path =
437 Path::new(&manifest_dir_string).join("../target").join(build_target).join(build_type);
438 return PathBuf::from(path);
439}
440
441fn configure_darwin_sysroot(builder: &mut cc::Build) {
442 let target_os = webrtc_sys_build::target_os();
443
444 let sdk = match target_os.as_str() {
445 "mac" => "macosx",
446 "ios-device" => "iphoneos",
447 "ios-simulator" => "iphonesimulator",
448 _ => panic!("Unsupported target_os: {}", target_os),
449 };
450
451 let clang_rt = match target_os.as_str() {
452 "mac" => "clang_rt.osx",
453 "ios-device" => "clang_rt.ios",
454 "ios-simulator" => "clang_rt.iossim",
455 _ => panic!("Unsupported target_os: {}", target_os),
456 };
457
458 println!("cargo:rustc-link-lib={}", clang_rt);
459 println!("cargo:rustc-link-arg=-ObjC");
460
461 let sysroot = Command::new("xcrun").args(["--sdk", sdk, "--show-sdk-path"]).output().unwrap();
462
463 let sysroot = String::from_utf8_lossy(&sysroot.stdout);
464 let sysroot = sysroot.trim();
465
466 let search_dirs = Command::new("cc").arg("--print-search-dirs").output().unwrap();
467
468 let search_dirs = String::from_utf8_lossy(&search_dirs.stdout);
469 for line in search_dirs.lines() {
470 if line.contains("libraries: =") {
471 let path = line.split('=').nth(1).unwrap();
472 let path = format!("{}/lib/darwin", path);
473 println!("cargo:rustc-link-search={}", path);
474 }
475 }
476
477 builder.flag(format!("-isysroot{}", sysroot).as_str());
478}
479
480fn configure_android_sysroot(builder: &mut cc::Build) {
481 let toolchain = webrtc_sys_build::android_ndk_toolchain().unwrap();
482 let sysroot = toolchain.join("sysroot").canonicalize().unwrap();
483 builder.flag(format!("-isysroot{}", sysroot.display()).as_str());
484}
485
486fn add_lazy_load_so(builder: &mut cc::Build, name: &str, libraries: Vec<String>) {
487 let target_arch = webrtc_sys_build::target_arch();
488 for lib_name in libraries {
489 let mut arch_dir = "x86_64-linux-gnu";
490 if target_arch.contains("arm64") {
491 arch_dir = "aarch64-linux-gnu";
492 }
493 let implib_file_c_name = "src/lazy_load_deps_for/".to_owned()
494 + name
495 + "/"
496 + arch_dir
497 + "/lib"
498 + &lib_name
499 + ".so.init.c";
500 let implib_file_asm_name = "src/lazy_load_deps_for/".to_owned()
501 + name
502 + "/"
503 + arch_dir
504 + "/lib"
505 + &lib_name
506 + ".so.tramp.S";
507 builder.file(implib_file_c_name).file(implib_file_asm_name);
508 }
509}
510
511/// Compile against the same hermetic libc++ that is baked into libwebrtc.a.
512///
513/// The Linux libwebrtc build sets `use_custom_libcxx=true`, so every std type in
514/// its public API lives in the `std::__Cr` ABI namespace with libc++ layouts.
515/// Using the host's libstdc++ here instead is not merely a mangling mismatch that
516/// the linker would catch: `std::span` is layout-different between the two, so a
517/// span handed to libwebrtc silently arrives with its pointer and size swapped.
518///
519/// Mirrors the flags in the WebRTC checkout's `build/config/c++/BUILD.gn`. The
520/// matching `_LIBCPP_*` defines come from webrtc.ninja via `webrtc_defines()`.
521fn configure_hermetic_libcxx(builder: &mut cc::Build, webrtc_include: &path::Path) {
522 let libcxx = webrtc_include.join("third_party/libc++/src/include");
523 let libcxxabi = webrtc_include.join("third_party/libc++abi/src/include");
524 if !libcxx.join("span").exists() {
525 panic!(
526 "hermetic libc++ headers missing from {}.\n\
527 This libwebrtc artifact predates use_custom_libcxx=true; rebuild it with \
528 build_linux.sh or point LK_CUSTOM_WEBRTC at a newer one.",
529 libcxx.display()
530 );
531 }
532
533 // Chromium's libc++ is clang-only. At _LIBCPP_ABI_VERSION 2 it marks unique_ptr
534 // and shared_ptr __attribute__((trivial_abi)), which GCC accepts and silently
535 // ignores (a -Wattributes warning that cc's `-w` swallows). That attribute
536 // changes the calling convention, not just layout: libwebrtc.a returns
537 // std::unique_ptr in a register, while a GCC caller reads it back from an sret
538 // slot the callee never wrote, yielding a garbage pointer at the first use.
539 if env::var_os("CXX").is_none() {
540 if Command::new("clang++").arg("--version").output().is_err() {
541 panic!(
542 "clang++ is required to build webrtc-sys on Linux: libwebrtc.a is built \
543 against Chromium's hermetic libc++, whose trivial_abi annotations GCC \
544 ignores, which silently breaks the calling convention for std::unique_ptr \
545 and std::shared_ptr. Install clang, or set CXX to a clang.",
546 );
547 }
548 builder.compiler("clang++");
549 }
550
551 check_clang_version(builder, &libcxx);
552
553 builder
554 .flag("-nostdinc++")
555 .flag(format!("-isystem{}", libcxx.display()))
556 .flag(format!("-isystem{}", libcxxabi.display()))
557 // Holds __config_site, which pins _LIBCPP_ABI_NAMESPACE=__Cr.
558 .include(webrtc_include.join("buildtools/third_party/libc++"));
559
560 // libc++/libc++abi are already archived into libwebrtc.a, so linking the
561 // host libstdc++ on top would only add a second, incompatible stdlib.
562 builder.cpp_link_stdlib(None);
563
564 // The cxx crate builds its own runtime (cxx.cc) with the host default stdlib,
565 // so the rust::String <-> std::string conversions it exports are mangled for
566 // libstdc++ and cannot satisfy the std::__Cr call sites in the generated
567 // bridges. Compile a second copy with the flags above to provide those.
568 // DEP_CXXBRIDGE1_HEADER is `cargo:HEADER` from the cxx crate: <root>/include/cxx.h.
569 let cxx_h = env::var("DEP_CXXBRIDGE1_HEADER")
570 .expect("cxx crate did not export HEADER; cannot locate its cxx.cc");
571 let cxx_root = path::Path::new(&cxx_h)
572 .parent()
573 .and_then(path::Path::parent)
574 .expect("unexpected DEP_CXXBRIDGE1_HEADER layout");
575 builder.file(cxx_root.join("src/cxx.cc"));
576}
577
578/// The hermetic libc++ tracks LLVM trunk, so it freely uses builtins that only
579/// exist in a recent clang (`__builtin_popcountg`, `__is_nothrow_convertible`,
580/// `__GCC_DESTRUCTIVE_SIZE`, ...). A compiler below its floor does not fail with
581/// "your clang is too old" — it fails deep inside <limits> and <span> with
582/// hundreds of lines about `dynamic_extent` not being a constant expression, in
583/// headers the user never wrote. Catch it up front instead.
584fn check_clang_version(builder: &cc::Build, libcxx: &path::Path) {
585 let min = libcxx_min_clang_major(libcxx);
586
587 let compiler = builder.get_compiler();
588 let defines = compiler
589 .to_command()
590 .args(["-dM", "-E", "-x", "c++", "/dev/null"])
591 .output()
592 .unwrap_or_else(|e| panic!("failed to run {}: {e}", compiler.path().display()));
593
594 let major = String::from_utf8_lossy(&defines.stdout).lines().find_map(|line| {
595 line.strip_prefix("#define __clang_major__ ").and_then(|v| v.trim().parse::<u32>().ok())
596 });
597
598 match major {
599 Some(major) if major >= min => {}
600 Some(major) => panic!(
601 "{} is clang {major}, but the hermetic libc++ shipped with this libwebrtc \
602 requires clang {min} or later. Install a newer clang and point CC/CXX at it, \
603 or use the exact toolchain libwebrtc was built with (see CR_CLANG_REVISION in \
604 the artifact's webrtc.ninja).",
605 compiler.path().display(),
606 ),
607 None => panic!(
608 "{} does not define __clang_major__, so it is not a clang. libwebrtc.a is built \
609 against Chromium's hermetic libc++, which requires clang {min} or later; GCC \
610 additionally ignores its trivial_abi annotations, silently breaking the calling \
611 convention for std::unique_ptr and std::shared_ptr.",
612 compiler.path().display(),
613 ),
614 }
615}
616
617/// libc++ states its own floor in `__configuration/compiler.h`, as
618/// `#if _LIBCPP_CLANG_VER < 2101` (major * 100 + minor). Read it from the
619/// artifact rather than hardcoding, so a libwebrtc bump moves the floor with it.
620fn libcxx_min_clang_major(libcxx: &path::Path) -> u32 {
621 const FALLBACK: u32 = 21;
622
623 let header = libcxx.join("__configuration/compiler.h");
624 let Ok(source) = std::fs::read_to_string(&header) else {
625 return FALLBACK;
626 };
627
628 source
629 .lines()
630 .find_map(|line| {
631 let (_, rest) = line.split_once("_LIBCPP_CLANG_VER < ")?;
632 let ver: u32 = rest.trim().parse().ok()?;
633 Some(ver / 100)
634 })
635 .unwrap_or(FALLBACK)
636}
637
638fn add_gio_headers(builder: &mut cc::Build) {
639 let webrtc_dir = webrtc_sys_build::webrtc_dir();
640 let target_arch = webrtc_sys_build::target_arch();
641 let target_arch_sysroot = match target_arch.as_str() {
642 "arm64" => "arm64",
643 "x64" => "amd64",
644 _ => panic!("unsupported arch"),
645 };
646 let sysroot_path = format!("include/build/linux/debian_bullseye_{target_arch_sysroot}-sysroot");
647 let sysroot = webrtc_dir.join(sysroot_path);
648 let glib_path = sysroot.join("usr/include/glib-2.0");
649 println!("cargo:info=add_gio_headers {}", glib_path.display());
650
651 builder.include(&glib_path);
652 let arch_specific_path = match target_arch.as_str() {
653 "x64" => "x86_64-linux-gnu",
654 "arm64" => "aarch64-linux-gnu",
655 _ => panic!("unsupported target"),
656 };
657
658 let glib_path_config = sysroot.join("usr/lib");
659 let glib_path_config = glib_path_config.join(arch_specific_path);
660 let glib_path_config = glib_path_config.join("glib-2.0/include");
661 builder.include(&glib_path_config);
662}