PHP 后台需要在接收 PNG 或 JPEG 后生成 ASTC 纹理和预览图。本文记录如何用 Bazel 将 Arm 的 ASTC 编码器编译成静态库,再通过 PHP-CPP 封装成 PHP 可调用的扩展。

本文记录 2021 年的构建环境,使用 PHP 7.1.9、PHP-CPP 2.1.4 和 astc-encoder 3.2。构建和加载扩展时应使用同一套 PHP 工具链。迁移到其他版本时,需要重新核对 PHP ABI 和库的构建选项。

如果要从 Go 调用 C++ 库,可以参考《CGO 基本用法与构建过程》。

0. 背景

基于以下诉求,需要将 astc-encoder C++ 库封装为 PHP 的扩展,提供对应的函数。

1. 构建 astc-encoder 静态库

astc-encoder 是用来处理图片的库,大部分都在于计算,极少部分涉及到平台区别,比如支持多线程处理,Linux 平台上需要 pthread 支持。我们要构建 PHP 扩展的.so文件,就需要先将 astc-encoder 构建静态库,封装函数使用其部分功能。本部分使用的构建代码,详见仓库 astc-encoder-bazel。

具体需求:

1.1 分析 astc-encoder 的项目结构

astc-encoder 提供的构建时使用 CMake 的,构建结果包括可执行文件和库。针对 x86-64 有三种构建版本,依赖不同的 CPU 指令集,来获得不同程度的性能提升(不愧是ARM-software下边的项目)。项目中的几个重要目录做下说明:

我们的需求涉及到 astc-encoder 的绝大部分功能。因此,接下来我会:

  1. 将 Source 中的文件(除了astcenccli_toplevel.cpp 和 astcenccli_toplevel_help.cpp)编译并归档成静态库
  2. 使用上述静态库,参考(裁剪)astcenccli_toplevel.cpp 文件,来封装可以使用的 C++ 函数

1.2 使用 Bazel 构建 astc 静态库

使用 Bazel 将 astc-encoder 作为一个外部项目引入,但由于其本身不是使用 Bazel 构建的,需要自己写一下 BUILD 文件或者在 build_file_content。根据上边的分析,WORKSPACE中这样写:

load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")

http_archive(
    name = "astc-encoder",
    build_file_content = """
cc_library(
    name = "astc-encoder",
    srcs = glob(["Source/*.cpp", "Source/*.h"], exclude=["Source/*toplevel*.cpp"]),
    includes = ["Source"],
    defines = ["NDEBUG"],
    visibility = ["//visibility:public"],
)
""",
    strip_prefix = "astc-encoder-3.2",
    urls = ["https://github.com/ARM-software/astc-encoder/archive/refs/tags/3.2.zip"],
)

1.3 封装函数并构建 astc_pdr 静态库

在项目中增加源文件和头文件:astc_pdr.cpp、astc_pdr.h,封装 astc_encoder。该函数会将输入的 png 或者 jpg 图片进行压缩,压缩成 .astc 文件,然后进行解压缩得到 .tga 文件用于预览。profile_str 接收 l、s、h、H,dimensions_str 接收 4x4、5x5、6x6、8x8、10x10、12x12,quality_str 接收exhaustive, thorough, medium, fast, fastest 等选项。

int astc_compress_and_compare(const std::string& profile_str,
                              const std::string& input_filename,
                              const std::string& compressed_output_filename,
                              const std::string& decompressed_output_filename,
                              const std::string& dimensions_str,
                              const std::string& quality_str);
// test:
// astc_compress_and_compare("l", "example.png", "example.astc", "example.tga", "6x6", "medium");

在 BUILD 文件中构建静态库:

cc_library(
    name = "astc_pdr",
    srcs = [
        "astc_pdr.cpp",
        "astc_pdr.h",
    ],
    copts = [
        "-pthread",
        "-static-libstdc++",
        "-DNDEBUG",
    ],
    deps = ["@astc-encoder"],
)

至此,已经完成了针对功能部分的封装,后边一节将会介绍将这种纯 C++ 的库封装成 PHP 可用的库。

这里经过两部构建,我们需要收集下静态库和头文件以供后续步骤的使用。

2. 使用 PHP-CPP 构建动态库

PHP-CPP 是 Copernica 公司开源的一个用于开发 PHP 扩展的 C++ 库。

因为 PHP-CPP 的构建过程是需要 PHP 的相关源文件的,因此这里的构建主要是在管理端的开发环境上进行的。另外,管理端使用的 PHP 版本是 v7.1.9,因为这个问题,只能使用指定 tag 的 PHP-CPP 库。

本部分使用的构建代码,详见仓库 astc-encoder-php。

2.1 构建 PHP-CPP 静态库

下载并解压:

curl -L -o PHP-CPP-2.1.4.zip https://codeload.github.com/CopernicaMarketingSoftware/PHP-CPP/zip/refs/tags/v2.1.4
unzip PHP-CPP-2.1.4.zip

修改 Makefile:

构建:

make -j release # release 带`-O2`

构建成功会产生两个库(我们只会用到静态库):

这里实际是可以 make install 指令将库和 include 文件直接放到系统目录中的,我这里为了尽量减少对环境的变更,没有这么操作。为了后边的需要,这里还需要建立一个软连接:

ln -s include phpcpp

2.2 导出为 PHP 函数

创建单独的文件夹,将之前的三个静态库和一个头文件放到该文件夹下。

编写 astc_pdr_php.cpp 文件,导出需要用到的C++函数:

#define _GLIBCXX_USE_CXX11_ABI 0
#include <phpcpp.h>

#include <string>

#include "astc_pdr.h"

Php::Value astc_encode(Php::Parameters &params) {
  std::string profile = params[0]; 
  std::string input_filename = params[1];
  std::string compressed_output_filename = params[2];
  std::string decompressed_output_filename = params[3];
  std::string dimensions_str = params[4];
  std::string quality_str = params[5];
  return astc_compress_and_compare(                     
      profile, input_filename, compressed_output_filename,       
      decompressed_output_filename, dimensions_str, quality_str);
}

// symbols are exported according to the "C" language
extern "C" {
// export the "get_module" function that will be called by the Zend engine
PHPCPP_EXPORT void *get_module() {
  // create extension
  static Php::Extension extension("astc_pdr", "1.0");
                         
  // define the functions
  extension.add<astc_encode>("astc_encode");
                            
  // return the module entry
  return extension.module();
}
}

编写Makefile:

PHP_CPP_BASE    = ../..
CPP             = g++
RM              = rm -f
CPP_FLAGS       = -Wall -c -I. -I${PHP_CPP_BASE} -I${PHP_CPP_BASE}/include -O2 -std=c++11 -D_GLIBCXX_USE_CXX11_ABI=0 -DNDEBUG
LD              = g++
LD_FLAGS        = -Wall -shared -O2 
RESULT          = astc_pdr.so
SOURCES         = $(wildcard *.cpp)
OBJECTS         = $(SOURCES:%.cpp=%.o)

all: ${OBJECTS} ${RESULT}

${RESULT}: ${OBJECTS}
	${LD} ${LD_FLAGS} -o $@ ${OBJECTS} ${PHP_CPP_BASE}/libphpcpp.a.2.1.4 libastc_pdr.a libastc-encoder.a -pthread libstdc++.a
    
clean:
	${RM} *.obj *~* ${OBJECTS} ${RESULT}

${OBJECTS}:
	${CPP} ${CPP_FLAGS} -fpic -o $@ ${@:%.o=%.cpp}

通过 make 指令,能得到 astc_pdr.so 这一扩展动态库。

3. PHP 使用 .so 扩展

确认 php 和 php-config 都来自目标 PHP 版本,再将动态库放到扩展目录:

cp astc_pdr.so "$(php-config --extension-dir)/"

修改 php.ini 文件,在 [PHP] 下边:

[PHP]
extension=astc_pdr.so

如果扩展用于 PHP-FPM,更新配置后按部署环境的方式重新加载 PHP-FPM。

编辑 PHP 测试脚本 astc_pdr.php:

<?php

astc_encode("l", "example.png", "example.astc", "example.tga", "6x6", "fastest");

下面是当时运行示例得到的输出。耗时和文件大小取决于输入图片及运行环境:

# time php astc_pdr.php
real    0m0.195s
user    0m0.356s
sys     0m0.024s
# du -sh example.*
40K	example.astc
32K	example.png
60K	example.tga