HarmonyOS Audio and Video – Lame MP3 Encoding Implementation
Background
MP3 is a broadly used audio compression format, famend for its environment friendly compression algorithm and in depth compatibility. It is likely one of the hottest audio codecs, and nearly all audio playback gadgets, cellular gadgets, computer systems, and audio software program assist MP3 playback. This makes MP3 a de facto customary format. Compared to compression efficiency, compatibility is extra essential in making certain MP3’s market share.
However, MP3 is a copyrighted encoding. Generally, cell phone producers don’t embrace MP3 {hardware} encoders however solely MP3 {hardware} decoders. The mostly used open-source MP3 smooth encoder out there is Lame. In this text, we are going to take Lame for instance to implement the MP3 smooth encoder from cross-platform compilation to integration into purposes in the entire course of.
Compiling Lame
There are typically three compilation strategies for third-party open-source C/C++ libraries:
- cmake
- make
- configure
Different construct scripts require the configuration of various variables. Lame is predicated on the Configure construct script, and you’ll view the configuration parameters by way of ./Configure -h. OpenHarmony offers a cross-compilation framework referred to as lycium. After configuring the data of third-party libraries in response to the template, you’ll be able to execute the construct script. The tpc_c_cplusplus challenge already contains the lame module within the thirdparty listing, and we are able to immediately compile it.
Enter the lycium listing and execute ./construct.sh lame to start out the compilation. After the compilation is accomplished, you’ll be able to see the person/lame listing below the lycium listing, the place the corresponding dynamic libraries have been compiled.
When compiling on a MacOS ARM model pc, an error happens. Check the log in tpc_c_cplusplus/thirdparty/lame/lame-3.100/armeabi-v7a-build/construct.log:
1 error generated.
1 error generated.
1 error generated.
../../mpglib/dct64_i386.c:34:10: deadly error: 'config.h' file not discovered
#embrace <config.h>
^~~~~~~~~~
make[2]: *** [tabinit.lo] Error 1
make[2]: *** Waiting for unfinished jobs....
make[2]: *** [common.lo] Error 1
make[2]: *** [interface.lo] Error 1
make[2]: *** [decode_i386.lo] Error 1
make[2]: *** [layer1.lo] Error 1
1 error generated.
1 error generated.
make[2]: *** [layer2.lo] Error 1
make[2]: *** [dct64_i386.lo] Error 1
1 error generated.
make[2]: *** [layer3.lo] Error 1
make[1]: *** [all-recursive] Error 1
** [tabinit.lo] Error 1
make[2]: *** Waiting for unfinished jobs....
make[2]: *** [common.lo] Error 1
make[2]: *** [interface.lo] Error 1
make[2]: *** [decode_i386.lo] Error 1
make[2]: *** [layer1.lo] Error 1
1 error generated.
1 error generated.
make[2]: *** [layer2.lo] Error 1
make[2]: *** [dct64_i386.lo] Error 1
1 error generated.
make[2]: *** [layer3.lo] Error 1
make[1]: *** [all-recursive] Error 1
make: *** [all] Error 2
"construct.log" 310L, 21047Bmake: *** [all] Error 2
The era of the config.h header file failed. Since Lame is predicated on Configure, it’s brought on by the mismatch of the variations of some dependent instruments. After altering to an Intel pc, the compilation was profitable:
Integrating into the HarmonyOS Project
Next, combine the compiled lame dynamic library into our challenge in a pre-compiled method.
First, create a local C++ challenge:
Create a brand new third_party/lame folder below the cpp listing, and duplicate the compiled .so recordsdata and the exported header recordsdata to this path:
Next, modify the CMakeLists.txt file to import the pre-compiled lame dynamic library and add the hyperlink:
add_library(lame SHARED IMPORTED)
set_target_properties(lame
PROPERTIES
IMPORTED_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/third_party/lame/libs/${OHOS_ARCH}/libmp3lame.so)
add_library(audio_engine SHARED napi_init.cpp)
target_link_libraries(audio_engine PUBLIC libace_napi.z.so lame)
To use the lame header recordsdata, you additionally must configure the header file search path:
include_directories(${NATIVERENDER_ROOT_PATH}
${NATIVERENDER_ROOT_PATH}/embrace
${NATIVERENDER_ROOT_PATH}/third_party/lame/embrace
)
After integrating into the challenge, it may be used.
Recording MP3 Audio Files
After the encoding library is built-in, it’s essential to encapsulate interfaces on the C++ facet for the TS facet to name. Here, we offer three fundamental interfaces:
- Create an encoder.
- Encode the info.
- Close the encoder.
Creating the Encoder
After creating the encoder with Lame, it’s essential to set the encoding parameters:
- Input audio sampling charge
- Input audio channel quantity
- Output sampling charge
- Output bit charge
- Output high quality
Define the initLame technique and supply 5 parameters:
size_t argc = 5;
napi_value args[5] = {nullptr};
napi_get_cb_info(env, information, &argc, args, nullptr, nullptr);
int inSamplerate;
napi_get_value_int32(env, args[0], &inSamplerate);
int inChannel;
napi_get_value_int32(env, args[1], &inChannel);
int outSamplerate;
napi_get_value_int32(env, args[2], &outSamplerate);
int outBitrate;
napi_get_value_int32(env, args[3], &outBitrate);
int high quality;
napi_get_value_int32(env, args[4], &high quality);
Next, configure the encoder:
lame = lame_init();
lame_set_in_samplerate(lame, inSamplerate);
lame_set_num_channels(lame, inChannel);// Input stream channels
lame_set_out_samplerate(lame, outSamplerate);
lame_set_brate(lame, outBitrate);
lame_set_quality(lame, high quality);
lame_init_params(lame);
Encoding Audio Data
The prototype of the Lame encoding operate is as follows:
/* * enter pcm information, output (possibly) mp3 frames. * This routine handles all buffering, resampling and filtering for you. * * return code variety of bytes output in mp3buf. Can be 0 * -1: mp3buf was too small * -2: malloc() drawback * -3: lame_init_params() not referred to as * -4: psycho acoustic issues * * The required mp3buf_size might be computed from num_samples, * samplerate and encoding charge, however here's a worst case estimate: * * mp3buf_size in bytes = 1.25*num_samples + 7200 * * I believe a tighter sure might be: (mt, March 2000) * MPEG1: * num_samples*(bitrate/8)/samplerate + 4*1152*(bitrate/8)/samplerate + 512 * MPEG2: * num_samples*(bitrate/8)/samplerate + 4*576*(bitrate/8)/samplerate + 256 * * however check first for those who use that! * * set mp3buf_size = 0 and LAME won't examine if mp3buf_size is * giant sufficient. * * NOTE: * if gfp->num_channels=2, however gfp->mode = 3 (mono), the L & R channels * might be averaged into the L channel earlier than encoding solely the L channel * This will overwrite the info in buffer_l[] and buffer_r[]. **/
int CDECL lame_encode_buffer (
lame_global_flags* gfp, /* international context deal with */
const brief int buffer_l [], /* PCM information for left channel */
const brief int buffer_r [], /* PCM information for proper channel */
const int nsamples, /* variety of samples per channel */
unsigned char* mp3buf, /* pointer to encoded MP3 stream */
const int mp3buf_size ); /* variety of legitimate octets on this stream */
It is critical to enter the left channel, proper channel information, the variety of samples for every channel, the output encoded information buffer, and the dimensions of the output encoded information buffer.
The NAPI interface requires three buffers to be enter:
static napi_value NAPI_Global_encodeLame(napi_env env, napi_callback_info information)
{
size_t argc = 4;
napi_value args[4] = {nullptr};
napi_get_cb_info(env, information, &argc, args, nullptr, nullptr);
napi_typedarray_type sort;// Data sort
napi_value left_input_buffer;
size_t byte_offset;// Data offset
size_t size;// Data byte measurement
napi_get_typedarray_info(env, args[0], &sort, &size, NULL, &left_input_buffer, &byte_offset);
void* leftBuffer;
size_t leftLength;
napi_get_arraybuffer_info(env, left_input_buffer, &leftBuffer, &leftLength);
napi_value right_input_buffer;
napi_get_typedarray_info(env, args[1], &sort, &size, NULL, &right_input_buffer, &byte_offset);
void* rightBuffer;
size_t rightLength;
napi_get_arraybuffer_info(env, right_input_buffer, &rightBuffer, &rightLength);
int samples;
napi_get_value_int32(env, args[2], &samples);
napi_value mp3_output_buffer;
napi_get_typedarray_info(env, args[3], &sort, &size, NULL, &mp3_output_buffer, &byte_offset);
void* mp3Buffer;
size_t mp3Length;
napi_get_arraybuffer_info(env, mp3_output_buffer, &mp3Buffer, &mp3Length);
int consequence = lame_encode_buffer(lame, (brief int*)leftBuffer, (brief int*)rightBuffer,
samples, (unsigned char*)mp3Buffer, mp3Length);
napi_value result_value;
napi_create_int32(env, consequence,&result_value);
return result_value;
}
The most important strategies used are napi_get_typedarray_info and napi_get_arraybuffer_info:
- On the Native C++ facet, it accepts the enter ArkTS Array. Through
napi_get_typedarray_info, the obtained information is handed into thetypedarrayarray to generate theinput_buffer. Then, by way ofnapi_get_arraybuffer_info, the array information is obtained. - On the ArkTS facet, it receives the Array returned by the Native C++ facet. Through
napi_create_arraybuffer, anarraybufferarray is created. According to the createdarraybuffer, atypedarrayis created by way ofnapi_create_typedarrayand thearraybufferis saved within theoutput_array. Then, thearraybufferis assigned a worth, and at last, theoutput_arrayis returned.
Closing the Encoder
Call the lame_close operate to shut the encoder. Before closing, it’s obligatory to make use of the lame_encode_flush technique to acquire the cached information within the encoder to make sure information integrity:
static napi_value NAPI_Global_flushLame(napi_env env, napi_callback_info information)
{
size_t argc = 1;
napi_value args[1] = {nullptr};
napi_get_cb_info(env, information, &argc, args, nullptr, nullptr);
napi_typedarray_type sort;// Data sort
napi_value output_buffer;
size_t byte_offset;// Data offset
size_t size;// Data byte measurement
napi_get_typedarray_info(env, args[0], &sort, &size, NULL, &output_buffer, &byte_offset);
void* outBuffer;
size_t outLength;
napi_get_arraybuffer_info(env, output_buffer, &outBuffer, &outLength);
int consequence = lame_encode_flush(lame, (unsigned char *)outBuffer, outLength);
napi_value result_value;
napi_create_int32(env, consequence,&result_value);
return result_value;
}
Problems Encountered
- After linking the
mp3lamelibrary and calling the native technique, an errorCannot learn property encodeLame of undefinedis reported. The purpose is that the compiledmp3lame.soaccommodates a model quantity. Directly eradicating the model quantity and copying it to the challenge causes this drawback. After retaining the very best digit of the model quantity, the issue is solved. - Thread points. Encoding is a time-consuming operation and must be processed in an unbiased thread. Create threads and caches on the C++ facet for interplay.
Summary
Due to copyright points, Android and iOS cell phones don’t immediately present MP3 {hardware} decoders. When recording MP3, the Lame third-party library is normally used. This article launched the entire technique of implementing MP3 software program encoding below HarmonyOS, from compiling the third-party library to integrating it into the challenge, encapsulating and calling it. Although HarmonyOS offers a {hardware} encoding technique for MP3, this text takes Lame for instance to supply the perfect apply for integrating third-party C++ libraries.
HI-FI News
through DEV Community https://dev.to
December 25, 2024 at 07:49AM
-
Product on sale
Audiophile Vinyl Records Cleaning BundleOriginal price was: €69.90.€59.90Current price is: €59.90. incl. VAT -
Product on sale
Easy Start Vinyl Records Cleaning KitOriginal price was: €69.90.€59.90Current price is: €59.90. incl. VAT -
Vinyl Records Cleaner Easy Groove Concentrate€34.95 incl. VAT -
Easy Groove Super Set€199.00 incl. VAT -
Easy Groove Enzycaster – vinyl records prewash cleaner€34.95 incl. VAT -
Easy Groove Extreme MK. II- vinyl records prewash cleaner€45.00 incl. VAT -
Vinyl Records Cleaner – Easy Groove Virgin Concentrate€35.00 incl. VAT -
Easy Groove Spray&Wipe vinyl records cleaner€34.95 incl. VAT











