C++ SDK

Updated at:

This topic describes how to use the C++ SDK from the Tingwu developer suite for real-time speech stream ingest. It also provides installation instructions and code samples for the SDK.

Prerequisites

Before you use the C++ SDK for speech stream ingest, read the Developer guide.

Source code download

Download tingwu-client-demo-cpp.zip. This file contains the Tingwu demo source code project. To compile and run the project, follow the instructions in the next section.

Compile and run

The Tingwu source code project currently supports compilation on the Linux platform. Follow these steps to compile and run the project:

  1. Install the compilation tools.

    • CMake (version 3.1 or later)

    • Glibc (version 2.5 or later)

    • GCC (version 4.1.2 or later)

  2. Install the dependencies.

    • Alibaba Cloud OpenAPI SDK. Compile and install only the core module of this project.

    • Alibaba Cloud Voice Service SDK.

    • Google Protobuf (version 3.14.0).

  3. In the root directory of the source code, open a Linux terminal and run the following script to run the Tingwu demo.

    ./build_linux.sh
    cd build/  
    ./tingwu-client

Sample code

Note
  • The audio file used in the sample has a sample rate of 16000 Hz.

  • The sample reads a local file to simulate a single-user meeting. For an online multi-user speech recognition meeting, you must construct each audio stream frame based on the MultiAudioFrame protobuf data structure. For more information, see Step 2 of Real-time speech stream ingest.

  • For the complete sample project, see the source code in the demo package.

// AsrAssistant class implementation
#include "AsrAssistant.h"
#include <algorithm>
#include <iostream>
#include <sstream>
#include <sys/time.h>

#include <uuid/uuid.h>
#include "HttpPopClient.h"
#include "logger.h"
#include "msg.pb.h"
#include "nlsClient.h"
#include "nlsEvent.h"
#include "json/json.h"
#include "speechTranscriberRequest.h"

using namespace AlibabaNls;
using namespace std;

namespace {

#define OPERATION_TIMEOUT_S 5

// Custom thread parameters.
    struct ParamStruct {
        std::string fileName;
        std::string token;
        std::string appkey;
    };

//@brief When start() is called and a connection is established with the cloud, the SDK's internal thread reports a started event.
//@param cbEvent The callback event structure. For more information, see nlsEvent.h.
//@param cbParam Custom callback parameter. The default value is NULL. You can customize the parameter as needed.
    void onTranscriptionStarted(NlsEvent *cbEvent, void *cbParam) {
        ParamCallBack *tmpParam = (ParamCallBack *) cbParam;
        // Sample code for printing or using custom user parameters.
        printf("onTranscriptionStarted: %d\n", tmpParam->userId);
        // The task ID of the current task. This helps locate issues.
        printf("onTranscriptionStarted: status code=%d, task id=%s\n", cbEvent->getStatusCode(), cbEvent->getTaskId());
        // Get the full server-side response.
        printf("onTranscriptionStarted: all response=%s\n", cbEvent->getAllResponse());
        // Notify the sending thread that start() was successful and that it can continue to send data.
        pthread_mutex_lock(&(tmpParam->mtxWord));
        pthread_cond_signal(&(tmpParam->cvWord));
        pthread_mutex_unlock(&(tmpParam->mtxWord));
    }

//@brief When the server-side detects the beginning of a sentence, the SDK's internal thread reports a SentenceBegin event.
//@param cbEvent The callback event structure. For more information, see nlsEvent.h.
//@param cbParam Custom callback parameter. The default value is NULL. You can customize the parameter as needed.
    void onSentenceBegin(NlsEvent *cbEvent, void *cbParam) {
        ParamCallBack *tmpParam = (ParamCallBack *) cbParam;
        // Sample code for printing or using custom user parameters.
        printf("onSentenceBegin: %d\n", tmpParam->userId);
        printf("onSentenceBegin: status code=%d, task id=%s, index=%d, time=%d\n", cbEvent->getStatusCode(),
               cbEvent->getTaskId(),
               cbEvent->getSentenceIndex(), // The sentence number, which increments starting from 1.
               cbEvent->getSentenceTime() // The duration of the audio that has been processed, in milliseconds.
        );
        // Get the full server-side response.
        printf("onSentenceBegin: all response=%s\n", cbEvent->getAllResponse());
    }

//@brief When the server-side detects the end of a sentence, the SDK's internal thread reports a SentenceEnd event.
//@param cbEvent The callback event structure. For more information, see nlsEvent.h.
//@param cbParam Custom callback parameter. The default value is NULL. You can customize the parameter as needed.
    void onSentenceEnd(NlsEvent *cbEvent, void *cbParam) {
        ParamCallBack *tmpParam = (ParamCallBack *) cbParam;
        // Sample code for printing or using custom user parameters.
        printf("onSentenceEnd: %d\n", tmpParam->userId);
        printf("onSentenceEnd: status code=%d, task id=%s, index=%d, time=%d, begin_time=%d, result=%s\n",
               cbEvent->getStatusCode(), cbEvent->getTaskId(),
               cbEvent->getSentenceIndex(), // The sentence number, which increments starting from 1.
               cbEvent->getSentenceTime(), // The duration of the audio that has been processed, in milliseconds.
               cbEvent->getSentenceBeginTime(), // The time of the corresponding SentenceBegin event.
               cbEvent->getResult()    // The complete recognition result for the current sentence.
        );
        // Get the full server-side response.
        printf("onSentenceEnd: all response=%s\n", cbEvent->getAllResponse());
    }

//@brief When the recognition result changes, the SDK's internal thread reports a ResultChanged event upon receiving the latest result from the cloud.
//@param cbEvent The callback event structure. For more information, see nlsEvent.h.
//@param cbParam Custom callback parameter. The default value is NULL. You can customize the parameter as needed.
    void onTranscriptionResultChanged(NlsEvent *cbEvent, void *cbParam) {
        ParamCallBack *tmpParam = (ParamCallBack *) cbParam;
        // Sample code for printing or using custom user parameters.
        printf("onTranscriptionResultChanged: %d\n", tmpParam->userId);
        printf("onTranscriptionResultChanged: status code=%d, task id=%s, index=%d, time=%d, result=%s\n",
               cbEvent->getStatusCode(), cbEvent->getTaskId(),
               cbEvent->getSentenceIndex(), // The sentence number, which increments starting from 1.
               cbEvent->getSentenceTime(), // The duration of the audio that has been processed, in milliseconds.
               cbEvent->getResult()    // The complete recognition result for the current sentence.
        );
        // Get the full server-side response.
        printf("onTranscriptionResultChanged: all response=%s\n", cbEvent->getAllResponse());
    }

//@brief When the server-side stops real-time audio stream recognition, the SDK's internal thread reports a Completed event.
//@note After a Completed event is reported, the SDK closes the recognition channel. At this point, calls to sendAudio return -1. Stop sending data.
//@param cbEvent The callback event structure. For more information, see nlsEvent.h.
//@param cbParam Custom callback parameter. The default value is NULL. You can customize the parameter as needed.
    void onTranscriptionCompleted(NlsEvent *cbEvent, void *cbParam) {
        ParamCallBack *tmpParam = (ParamCallBack *) cbParam;
        // Sample code for printing or using custom user parameters.
        printf("onTranscriptionCompleted: %d\n", tmpParam->userId);
        printf("onTranscriptionCompleted: status code=%d, task id=%s\n", cbEvent->getStatusCode(),
               cbEvent->getTaskId());
    }

//@brief If an exception occurs during the recognition process (including start(), send(), and stop()), the SDK's internal thread reports a TaskFailed event.
//@note After a TaskFailed event is reported, the SDK closes the recognition channel. At this point, calls to sendAudio return -1. Stop sending data.
//@param cbEvent The callback event structure. For more information, see nlsEvent.h.
//@param cbParam Custom callback parameter. The default value is NULL. You can customize the parameter as needed.
    void onTaskFailed(NlsEvent *cbEvent, void *cbParam) {
        ParamCallBack *tmpParam = (ParamCallBack *) cbParam;
        // Sample code for printing or using custom user parameters.
        printf("onTaskFailed: %d\n", tmpParam->userId);
        printf("onTaskFailed: status code=%d, task id=%s, error message=%s\n", cbEvent->getStatusCode(),
               cbEvent->getTaskId(), cbEvent->getErrorMessage());
        // Get the full server-side response.
        //printf("onTaskFailed: all response=%s\n", cbEvent->getAllResponse());
    }

//@brief The SDK's internal thread reports a speech form result event.
//@param cbEvent The callback event structure. For more information, see nlsEvent.h.
//@param cbParam Custom callback parameter. The default value is NULL. You can customize the parameter as needed.
    void onSentenceSemantics(NlsEvent *cbEvent, void *cbParam) {
        ParamCallBack *tmpParam = (ParamCallBack *) cbParam;
        // Sample code for printing or using custom user parameters.
        printf("onSentenceSemantics: %d\n", tmpParam->userId);
        // Get the full server-side response.
        printf("onSentenceSemantics: all response=%s\n", cbEvent->getAllResponse());
    }

//@brief When recognition ends or an exception occurs, the connection channel is closed, and the SDK's internal thread reports a ChannelClosed event.
//@param cbEvent The callback event structure. For more information, see nlsEvent.h.
//@param cbParam Custom callback parameter. The default value is NULL. You can customize the parameter as needed.
    void onChannelClosed(NlsEvent *cbEvent, void *cbParam) {
        if (cbParam) {
            ParamCallBack *tmpParam = (ParamCallBack *) cbParam;
            // Notify the sending thread that the final recognition result has been returned and that stop() can be called.
            pthread_mutex_lock(&(tmpParam->mtxWord));
            pthread_cond_signal(&(tmpParam->cvWord));
            pthread_mutex_unlock(&(tmpParam->mtxWord));
            delete tmpParam; // The recognition process is complete. Release the callback parameters.
        }
    }

    /**
 * @brief All information returned from the server-side is sent through this callback.
 * @param cbEvent The callback event structure. For more information, see nlsEvent.h.
 * @param cbParam Custom callback parameter. The default value is NULL. You can customize the parameter as needed.
 * @return
*/
    void onMessage(AlibabaNls::NlsEvent *cbEvent, void *cbParam) {
        std::cout << "onMessage: All response:"
                  << cbEvent->getAllResponse() << std::endl;
        std::cout << "onMessage: msg tyep:"
                  << cbEvent->getMsgType() << std::endl;

        // The JSON data needs to be parsed here.
        int result = cbEvent->parseJsonMsg(true);
        if (result) {
            std::cout << "onMessage: parseJsonMsg failed:"
                      << result << std::endl;
        } else {
            if (cbParam) {
                ParamCallBack *tmpParam = (ParamCallBack *) cbParam;
                switch (cbEvent->getMsgType()) {
                    case AlibabaNls::NlsEvent::TaskFailed:
                        break;
                    case AlibabaNls::NlsEvent::TranscriptionStarted:
                        // Notify the sending thread that start() was successful and that it can continue to send data.
                        pthread_mutex_lock(&(tmpParam->mtxWord));
                        pthread_cond_signal(&(tmpParam->cvWord));
                        pthread_mutex_unlock(&(tmpParam->mtxWord));
                        break;
                    case AlibabaNls::NlsEvent::Close:
                        // Notify the sending thread that the final recognition result has been returned and that stop() can be called.
                        pthread_mutex_lock(&(tmpParam->mtxWord));
                        pthread_cond_signal(&(tmpParam->cvWord));
                        pthread_mutex_unlock(&(tmpParam->mtxWord));
                        break;
                }
            }
        }
    }
}// namespace


namespace {
bool urlIsOk(const std::string& url) {
    LOGD("url: %s ", url.c_str());
  if (url.size() < 4) {
    return false;
  }
  std::string str = url.substr(0, 2).c_str();
  transform(str.begin(), str.end(), str.begin(), ::tolower);
  return "ws" == str;
}
}  // namespace

std::string InitParams::toString() const {
  std::stringstream ss;
  ss << "{\"accesskey\":\"" << _accesskey << "\",\"secret\":\"" << _access_secret
     << "\",\"sdk_log_name\":\"" << _sdk_log_name<< "\",\"sdk_log_level\":" << _sdk_log_level
     << ",\"version\":\""<< _version << "\",\"domain\":\"" << _domain << "\",\"resource_path\":\"" << _resource_path
     << "\",\"region\":\""<< _region << "\",\"scheme\":\"" << _scheme << "\"}";

  return ss.str();
}

std::string AsrAssistant::generateUuid() {
    uuid_t uu;
    uuid_generate(uu);
    char buf[1024];
    uuid_unparse(uu, buf);
    std::string uuid = buf;
    return uuid;
}
void AsrAssistant::sendTranslateConfigUpdateDirective(){
    Json::Value header;
    header["name"] = "UpdateConfg";

    Json::Value payload;
    payload["translate_result_enabled"] = false;
    payload["translate_languages"] = "en";
    payload["instruction_id"] = generateUuid();

    Json::Value root;
    root["header"] = header;
    root["payload"] = payload;

    Json::FastWriter writer;
    std::string json_str=writer.write(root);
    std::cout<<"json_str: "<<json_str<<std::endl;
    // Control the translation switch during the meeting by sending a custom message.
    _request->control(json_str.c_str());
}

bool AsrAssistant::start(const std::string& doc_json_str,const std::string& first_frame_time) {
  LOGD("%s : AsrAssistant::start", _session_id.c_str());
  long start_time = NOW;
  for (int i = 0; i < 3; ++i) {
    _url = HttpPopClient::getInstance().getAsrUrl(doc_json_str,meetingId);
    if (urlIsOk(_url)) {
      break;
    }
  }
  if (!urlIsOk(_url)) {
    LOGE("%s : get url fail", _session_id.c_str());
    return false;
  }
  LOGD("%s : get url took: %ld ", _session_id.c_str(), NOW - start_time);
  LOGD("%s : url: %s ", _session_id.c_str(), _url.c_str());
    //LOGD("%s : namespace: %s ", _session_id.c_str(), RFASR_NAMESPACE);
  _request = NlsClient::getInstance()->createTranscriberRequest("cpp",true);
  if (nullptr == _request) {
      LOGE("%s : createTranscriberRequest failed", _session_id.c_str());
      return false;
  }

    // Release before the thread exits.
    cbParam = new ParamCallBack();
    if (!cbParam) {
        return NULL;
    }
//    _request->setOnTranscriptionStarted(onTranscriptionStarted, cbParam);                // Set the recognition started callback function
//    _request->setOnTranscriptionResultChanged(onTranscriptionResultChanged, cbParam);    // Set the recognition result changed callback function
//    _request->setOnTranscriptionCompleted(onTranscriptionCompleted, cbParam);            // Set the speech transcription completed callback function
//    _request->setOnSentenceBegin(onSentenceBegin, cbParam);                              // Set the sentence begin callback function
//    _request->setOnSentenceEnd(onSentenceEnd, cbParam);                                  // Set the sentence end callback function
//    _request->setOnTaskFailed(onTaskFailed, cbParam);                                    // Set the task failed callback function
//    _request->setOnChannelClosed(onChannelClosed, cbParam);                              // Set the channel closed callback function

    // Set the callback function for all server-side return messages.
    _request->setOnMessage(onMessage, cbParam);
    // Enable the callback function for all server-side return messages. Other callbacks (except OnBinaryDataRecved) become invalid.
    _request->setEnableOnMessage(true);

    // If you pause and then resume recognition, and AudioOutputEnabled was set to false or not set when the meeting was created, you must set the meeting time offset for resuming recognition (in milliseconds).
//    std::string json_first_frame_time="{\"tw_time_offset\": \"xxx\"}";
//    _request->setPayloadParam(json_first_frame_time.c_str());

    // You can modify the translation configuration before starting recognition.
    Json::FastWriter writer;
    bool translateResultEnabled = true;
    if (translateResultEnabled) {
        Json::Value json_translate_result_enabled;
        json_translate_result_enabled["translate_result_enabled"] = true;
        std::string str_json_translate_result_enabled = writer.write(json_translate_result_enabled);
        _request->setPayloadParam(str_json_translate_result_enabled.c_str());

        Json::Value json_translate_languages;
        json_translate_languages["translate_languages"] = "en";
        std::string str_json_translate_languages = writer.write(json_translate_languages);
        _request->setPayloadParam(str_json_translate_languages.c_str());
    } else {
        Json::Value json_translate_result_enabled;
        json_translate_result_enabled["translate_result_enabled"] = false;
        std::string str_json_translate_result_enabled = writer.write(json_translate_result_enabled);
        _request->setPayloadParam(str_json_translate_result_enabled.c_str());
    }

    _request->setUrl(_url.c_str());

  start_time = NOW;
  if (_request->start() < 0) {
    LOGE("%s : start fail", _session_id.c_str());
    NlsClient::getInstance()->releaseTranscriberRequest(_request);
    return false;
  }
  LOGD("%s : : AsrAssistant::start success, took:: %ld ", _session_id.c_str(),
       NOW - start_time);


    // Wait for the started event to return before sending.
    std::cout << "wait started callback." << std::endl;
    /*
    * The voice server may not be able to process the current request in time and may not return any callback within 10 seconds.
    * It then returns a TaskFailed callback after 10 seconds. Therefore, a timeout mechanism is required.
    */
    struct timespec outtime;
    struct timeval now;
    gettimeofday(&now, NULL);
    outtime.tv_sec = now.tv_sec + OPERATION_TIMEOUT_S;
    outtime.tv_nsec = now.tv_usec * 1000;
    pthread_mutex_lock(&(cbParam->mtxWord));
    if (ETIMEDOUT == pthread_cond_timedwait(&(cbParam->cvWord), &(cbParam->mtxWord), &outtime)) {
        std::cout << "start timeout" << std::endl;
        pthread_mutex_unlock(&(cbParam->mtxWord));
        _request->cancel();
        NlsClient::getInstance()->releaseTranscriberRequest(_request);
        return false;
    }
    pthread_mutex_unlock(&(cbParam->mtxWord));
    return true;
}

void AsrAssistant::stop() {
  if (nullptr != _request) {
      int ret = _request->stop();
      LOGD("%s : stop res:%d", _session_id.c_str(), ret);

      /*
       * Recognition is complete. Release the request object.
       */
      if (ret == 0) {
          std::cout << "wait closed callback." << std::endl;
          /*
           * The voice server may not be able to process the current request in time and may not return any callback within 10 seconds.
           * It then returns a TaskFailed callback after 10 seconds with the error message:
           * "Gateway:IDLE_TIMEOUT:Websocket session is idle for too long time, the last directive is 'StopTranscriber'!"
           * Therefore, a timeout mechanism is required.
           */
          struct timespec outtime;
          struct timeval now;
          gettimeofday(&now, NULL);
          outtime.tv_sec = now.tv_sec + OPERATION_TIMEOUT_S;
          outtime.tv_nsec = now.tv_usec * 1000;
          // Wait for the closed event before releasing to prevent a crash.
          pthread_mutex_lock(&(cbParam->mtxWord));
          if (ETIMEDOUT == pthread_cond_timedwait(&(cbParam->cvWord), &(cbParam->mtxWord), &outtime)) {
              std::cout << "stop timeout" << std::endl;
              //pthread_mutex_unlock(&(cbParam->mtxWord));
          }
          pthread_mutex_unlock(&(cbParam->mtxWord));
      } else {
          std::cout << "ret is " << ret << std::endl;
      }
      NlsClient::getInstance()->releaseTranscriberRequest(_request);
      _request=nullptr;
  }
  HttpPopClient::getInstance().stopMeetingTrans(meetingId);
}

AsrAssistant::AsrAssistant(const std::string& session_id)
    : _session_id(session_id) {}

AsrAssistant::~AsrAssistant() {}

bool AsrAssistant::sendAudio(const PB::MultiAudioFrame& frame) {
  if (nullptr == _request) return false;
  std::string pb_str;
  if (!frame.SerializeToString(&pb_str)) {
    LOGE("%s generate pb package fail", _session_id.c_str());
    return false;
  }
  long start = NOW;
  int ret =
      _request->sendAudio((const uint8_t*)pb_str.c_str(), pb_str.size());
  long end = NOW;
  if (ret < 0) {
    LOGE("%s sendaudio,ret:%d,start:%ld,end:%ld,diff:%ld,request:%p",
         _session_id.c_str(), ret, start, end, end - start, _request);
  }
  return ret >= 0;
}

bool AsrAssistant::sendAudio(const char* data,size_t length) {
    if (nullptr == _request) return false;
    long start = NOW;
    int ret =
            _request->sendAudio((const uint8_t*)data,length);
    long end = NOW;
    if (ret < 0) {
        LOGE("%s sendaudio,ret:%d,start:%ld,end:%ld,diff:%ld,request:%p",
             _session_id.c_str(), ret, start, end, end - start, _request);
    }
    return ret >= 0;
}

bool AsrAssistant::init(InitParams param) {
  LOGD("AsrAssistant::init(%s)", param.toString().c_str());
  LogLevel log_level = LogLevel::LogInfo;
  switch (param._sdk_log_level) {
    case 1:
      log_level = LogLevel::LogError;
      break;

    case 2:
      log_level = LogLevel::LogWarning;
      break;

    case 4:
      log_level = LogLevel::LogDebug;
      break;
  }

  if (-1 == NlsClient::getInstance()->setLogConfig(param._sdk_log_name.c_str(),
                                                   log_level, 2000)) {
    return false;
  }

  NlsClient::getInstance()->startWorkThread(1);

  HttpPopClient::getInstance().setVersion(param._version);
  HttpPopClient::getInstance().setScheme(param._scheme);
  HttpPopClient::getInstance().setDomain(param._domain);
  //HttpPopClient::getInstance().setResourcePath("/api/brk/meeting/create/");
  HttpPopClient::getInstance().init(param._accesskey, param._access_secret,
                                    param._region);
  return true;
}

void AsrAssistant::unInit() { NlsClient::releaseInstance(); }

void AsrAssistant::errorHappened(int state_code, const std::string& msg) {
  if (nullptr != _error_callback) {
    _error_callback(_session_id, state_code, msg);
  }
}

AsrAssistant& AsrAssistant::setAudioFormat(const std::string& format) {
  _format = format;
  return *this;
}

AsrAssistant& AsrAssistant::setSampleRate(int sample_rate) {
  _sample_rate = sample_rate;
  return *this;
}

AsrAssistant& AsrAssistant::setFrameTime(int frame_time) {
  _frame_time = frame_time;
  return *this;
}

AsrAssistant& AsrAssistant::setErrorCallBack(
    std::function<void(std::string session_id, int status_code,
                       std::string msg)>
        callback) {
  _error_callback = callback;
  return *this;
}


// Single-user real-time meeting recognition
void func(int thread_id, int id) {
  std::string session_id = std::string("test_lala_") +
                           std::to_string(thread_id) + "_" + std::to_string(id);
  AsrAssistant asr(session_id);
  int sample_rate = 16000;
  int p_time = 100;  // ms
  int process_size = sample_rate * 2 * p_time / 1000;
  int num = data_len / process_size;
  if (data_len % process_size != 0) {
    ++num;
  }

  std::string uuid = generateUuid();

    Json::Value root;
    root["MeetingKey"] = uuid;
    root["AudioFormat"] = "pcm";
    root["AudioSampleRate"] = 16000;
    root["AudioBitRate"] = 16;
    root["AudioLanguage"] = "cn";
    root["AppKey"] = appkey;

  asr.setFrameTime(p_time);
  asr.setSampleRate(sample_rate);
//  if (send_buffer_limit > 0) {
//    asr.setSendBufferLimit(send_buffer_limit);
//  }
  Json::FastWriter writer;
  std::string first_frame_time=std::to_string(getCurrentTime());
  if (!asr.start(writer.write(root),first_frame_time)) {
    std::cout << "start fail" << std::endl;
    return;
  }
  int tstCount = 0;
  int speaker = 0;
  for (int j = 0; j < num; ++j) {
    int size = process_size;
    if (j == num - 1) {
      if (data_len % process_size > 0) {
        size = data_len % process_size;
      }
    }
      if (asr.sendAudio(data + process_size * j,size)) {
          std::this_thread::sleep_for(milliseconds(p_time));
      } else {
          LOGE("sessionid:%s,uuid:%s send failed,exit,time:%ld", session_id.c_str(),
               uuid.c_str(), NOW);
          std::this_thread::sleep_for(milliseconds(p_time));
          break;
      }
      // You can modify the translation configuration as needed during the recognition process. Do not use recursive invocation. This is only an example to show that the call can be made during speech stream ingest.
      //asr.sendTranslateConfigUpdateDirective();
  }
  LOGD("sessionid:%s,uuid:%s prepare stop,time:%ld", session_id.c_str(),
       uuid.c_str(), NOW);
  asr.stop();
}