| 5 |
| #include <stdlib.h> |
| 6 | #include <time.h> |
| 7 | #include <opusfile.h> |
| 8 | #include <math.h> |
| 9 | #include <rnnoise.h> |
| 10 | #include "c_utils.h" |
| 11 | #include "libavformat/avformat.h" |
| 12 | #include "libavcodec/avcodec.h" |
| 13 |
| 14 | typedef struct { |
| 15 | int version; |
| 16 | int channels; /* Number of channels: 1..255 */ |
| 17 | int preskip; |
| 18 | ogg_uint32_t input_sample_rate; |
| 19 | int gain; /* in dB S7.8 should be zero whenever possible */ |
| 20 | int channel_mapping; |
| 21 | /* The rest is only used if channel_mapping != 0 */ |
| 22 | int nb_streams; |
| 23 | int nb_coupled; |
| 24 | unsigned char stream_map[255]; |
| 25 | } OpusHeader; |
| 26 |
| 27 | typedef struct { |
| 28 | unsigned char *data; |
| 29 | int maxlen; |
| 30 | int pos; |
| 31 | } Packet; |
| 32 |
| 33 | typedef struct { |
| 34 | const unsigned char *data; |
| 35 | int maxlen; |
| 36 | int pos; |
| 37 | } ROPacket; |
| 38 |
| 39 | typedef struct { |
| 40 | void *readdata; |
| 41 | opus_int64 total_samples_per_channel; |
| 42 | int rawmode; |
| 43 | int channels; |
| 44 | long rate; |
| 45 | int gain; |
| 46 | int samplesize; |
| 47 | int endianness; |
| 48 | char *infilename; |
| 49 | int ignorelength; |
| 50 | int skip; |
| 51 | int extraout; |
| 52 | char *comments; |
| 53 | int comments_length; |
| 54 | int copy_comments; |
| 55 | } oe_enc_opt; |
| 56 |
| 57 | static int write_uint32(Packet *p, ogg_uint32_t val) { |
| 58 | if (p->pos > p->maxlen - 4) { |
| 59 | return 0; |
| 60 | } |
| 61 | p->data[p->pos ] = (val ) & 0xFF; |
| 62 | p->data[p->pos+1] = (val>> 8) & 0xFF; |
| 63 | p->data[p->pos+2] = (val>>16) & 0xFF; |
| 64 | p->data[p->pos+3] = (val>>24) & 0xFF; |
| 65 | p->pos += 4; |
| 66 | return 1; |
| 67 | } |
| 68 |
| 69 | static int write_uint16(Packet *p, ogg_uint16_t val) { |
| 70 | if (p->pos > p->maxlen-2) { |
| 71 | return 0; |
| 72 | } |
| 73 | p->data[p->pos ] = (val ) & 0xFF; |
| 74 | p->data[p->pos+1] = (val>> 8) & 0xFF; |
| 75 | p->pos += 2; |
| 76 | return 1; |
| 77 | } |
| 78 |
| 79 | static int write_chars(Packet *p, const unsigned char *str, int nb_chars) |
| 80 | { |
| 81 | int i; |
| 82 | if (p->pos>p->maxlen-nb_chars) |
| 83 | return 0; |
| 84 | for (i=0;i<nb_chars;i++) |
| 85 | p->data[p->pos++] = str[i]; |
| 86 | return 1; |
| 87 | } |
| 88 |
| 89 | static int read_uint32(ROPacket *p, ogg_uint32_t *val) |
| 90 | { |
| 91 | if (p->pos>p->maxlen-4) |
| 92 | return 0; |
| 93 | *val = (ogg_uint32_t)p->data[p->pos ]; |
| 94 | *val |= (ogg_uint32_t)p->data[p->pos+1]<< 8; |
| 95 | *val |= (ogg_uint32_t)p->data[p->pos+2]<<16; |
| 96 | *val |= (ogg_uint32_t)p->data[p->pos+3]<<24; |
| 97 | p->pos += 4; |
| 98 | return 1; |
| 99 | } |
| 100 |
| 101 | static int read_uint16(ROPacket *p, ogg_uint16_t *val) |
| 102 | { |
| 103 | if (p->pos>p->maxlen-2) |
| 104 | return 0; |
| 105 | *val = (ogg_uint16_t)p->data[p->pos ]; |
| 106 | *val |= (ogg_uint16_t)p->data[p->pos+1]<<8; |
| 107 | p->pos += 2; |
| 108 | return 1; |
| 109 | } |
| 110 |
| 111 | static int read_chars(ROPacket *p, unsigned char *str, int nb_chars) |
| 112 | { |
| 113 | int i; |
| 114 | if (p->pos>p->maxlen-nb_chars) |
| 115 | return 0; |
| 116 | for (i=0;i<nb_chars;i++) |
| 117 | str[i] = p->data[p->pos++]; |
| 118 | return 1; |
| 119 | } |
| 120 |
| 121 | int opus_header_to_packet(const OpusHeader *h, unsigned char *packet, int len) { |
| 122 | int i; |
| 123 | Packet p; |
| 124 | unsigned char ch; |
| 125 |
| 126 | p.data = packet; |
| 127 | p.maxlen = len; |
| 128 | p.pos = 0; |
| 129 | if (len < 19) { |
| 130 | return 0; |
| 131 | } |
| 132 | if (!write_chars(&p, (const unsigned char *)"OpusHead", 8)) { |
| 133 | return 0; |
| 134 | } |
| 135 |
| 136 | ch = 1; |
| 137 | if (!write_chars(&p, &ch, 1)) { |
| 138 | return 0; |
| 139 | } |
| 140 |
| 141 | ch = h->channels; |
| 142 | if (!write_chars(&p, &ch, 1)) { |
| 143 | return 0; |
| 144 | } |
| 145 |
| 146 | if (!write_uint16(&p, h->preskip)) { |
| 147 | return 0; |
| 148 | } |
| 149 |
| 150 | if (!write_uint32(&p, h->input_sample_rate)) { |
| 151 | return 0; |
| 152 | } |
| 153 |
| 154 | if (!write_uint16(&p, h->gain)) { |
| 155 | return 0; |
| 156 | } |
| 157 |
| 158 | ch = h->channel_mapping; |
| 159 | if (!write_chars(&p, &ch, 1)) { |
| 160 | return 0; |
| 161 | } |
| 162 |
| 163 | if (h->channel_mapping != 0) { |
| 164 | ch = h->nb_streams; |
| 165 | if (!write_chars(&p, &ch, 1)) { |
| 166 | return 0; |
| 167 | } |
| 168 |
| 169 | ch = h->nb_coupled; |
| 170 | if (!write_chars(&p, &ch, 1)) { |
| 171 | return 0; |
| 172 | } |
| 173 |
| 174 | /* Multi-stream support */ |
| 175 | for (i = 0; i < h->channels; i++) { |
| 176 | if (!write_chars(&p, &h->stream_map[i], 1)) { |
| 177 | return 0; |
| 178 | } |
| 179 | } |
| 180 | } |
| 181 |
| 182 | return p.pos; |
| 183 | } |
| 184 |
| 185 | #define writeint(buf, base, val) do { buf[base + 3] = ((val) >> 24) & 0xff; \ |
| 186 | buf[base + 2]=((val) >> 16) & 0xff; \ |
| 187 | buf[base + 1]=((val) >> 8) & 0xff; \ |
| 188 | buf[base] = (val) & 0xff; \ |
| 189 | } while(0) |
| 190 |
| 191 | static void comment_init(char **comments, int *length, const char *vendor_string) { |
| 192 | // The 'vendor' field should be the actual encoding library used |
| 193 | size_t vendor_length = strlen(vendor_string); |
| 194 | int user_comment_list_length = 0; |
| 195 | size_t len = 8 + 4 + vendor_length + 4; |
| 196 | char *p = (char *)malloc(len); |
| 197 | memcpy(p, "OpusTags", 8); |
| 198 | writeint(p, 8, vendor_length); |
| 199 | memcpy(p + 12, vendor_string, vendor_length); |
| 200 | writeint(p, 12 + vendor_length, user_comment_list_length); |
| 201 | *length = len; |
| 202 | *comments = p; |
| 203 | } |
| 204 |
| 205 | static void comment_pad(char **comments, int* length, size_t amount) { |
| 206 | if (amount > 0) { |
| 207 | char *p = *comments; |
| 208 | // Make sure there is at least amount worth of padding free, and round up to the maximum that fits in the current ogg segments |
| 209 | size_t newlen = (*length + amount + 255) / 255 * 255 - 1; |
| 210 | p = realloc(p, newlen); |
| 211 | for (int32_t i = *length; i < newlen; i++) { |
| 212 | p[i] = 0; |
| 213 | } |
| 214 | *comments = p; |
| 215 | *length = newlen; |
| 216 | } |
| 217 | } |
| 218 |
| 219 | static int writeOggPage(ogg_page *page, FILE *os) { |
| 220 | int written = fwrite(page->header, sizeof(unsigned char), (size_t) page->header_len, os); |
| 221 | written += fwrite(page->body, sizeof(unsigned char), (size_t) page->body_len, os); |
| 222 | return written; |
| 223 | } |
| 224 |
| 225 | const opus_int32 bitrate = 30 * 1024; |
| 226 | static const int opus_application = OPUS_APPLICATION_AUDIO; |
| 227 | const opus_int32 frame_size = 960; |
| 228 | const int with_cvbr = 1; |
| 229 | const int max_ogg_delay = 0; |
| 230 | const int comment_padding = 512; |
| 231 |
| 232 | opus_int32 rate = 48000; |
| 233 | opus_int32 coding_rate = 48000; |
| 234 |
| 235 | ogg_int32_t _packetId; |
| 236 | OpusEncoder *_encoder = 0; |
| 237 | uint8_t *_packet = 0; |
| 238 | ogg_stream_state os; |
| 239 | const char *_filePath; |
| 240 | FILE *_fileOs = 0; |
| 241 | oe_enc_opt inopt; |
| 242 | OpusHeader header; |
| 243 | opus_int32 min_bytes; |
| 244 | int max_frame_bytes; |
| 245 | ogg_packet op; |
| 246 | ogg_page og; |
| 247 | opus_int64 bytes_written; |
| 248 | opus_int64 pages_out; |
| 249 | opus_int64 total_samples; |
| 250 | ogg_int64_t enc_granulepos; |
| 251 | ogg_int64_t last_granulepos; |
| 252 | int size_segments; |
| 253 | int last_segments; |
| 254 | int serialno; |
| 255 |
| 256 | void cleanupRecorder() { |
| 257 |
| 258 | if (_fileOs) { |
| 259 | while (ogg_stream_flush(&os, &og)) { |
| 260 | writeOggPage(&og, _fileOs); |
| 261 | } |
| 262 | } else { |
| 263 | ogg_stream_flush(&os, &og); |
| 264 | } |
| 265 |
| 266 | if (_encoder) { |
| 267 | opus_encoder_destroy(_encoder); |
| 268 | _encoder = 0; |
| 269 | } |
| 270 |
| 271 | ogg_stream_clear(&os); |
| 272 |
| 273 | if (_packet) { |
| 274 | free(_packet); |
| 275 | _packet = 0; |
| 276 | } |
| 277 |
| 278 | if (_fileOs) { |
| 279 | fclose(_fileOs); |
| 280 | _fileOs = 0; |
| 281 | } |
| 282 |
| 283 | _packetId = -1; |
| 284 | bytes_written = 0; |
| 285 | pages_out = 0; |
| 286 | total_samples = 0; |
| 287 | enc_granulepos = 0; |
| 288 | size_segments = 0; |
| 289 | last_segments = 0; |
| 290 | last_granulepos = 0; |
| 291 | if (_filePath) { |
| 292 | free(_filePath); |
| 293 | _filePath = 0; |
| 294 | } |
| 295 | memset(&os, 0, sizeof(ogg_stream_state)); |
| 296 | memset(&inopt, 0, sizeof(oe_enc_opt)); |
| 297 | memset(&header, 0, sizeof(OpusHeader)); |
| 298 | memset(&op, 0, sizeof(ogg_packet)); |
| 299 | memset(&og, 0, sizeof(ogg_page)); |
| 300 | } |
| 301 |
| 302 | int initRecorder(const char *path, opus_int32 sampleRate) { |
| 303 | cleanupRecorder(); |
| 304 |
| 305 | coding_rate = sampleRate; |
| 306 | rate = sampleRate; |
| 307 |
| 308 | if (!path) { |
| 309 | LOGE("path is null"); |
| 310 | return 0; |
| 311 | } |
| 312 |
| 313 | int length = strlen(path); |
| 314 | _filePath = (char*) malloc(length + 1); |
| 315 | strcpy(_filePath, path); |
| 316 |
| 317 | _fileOs = fopen(path, "w"); |
| 318 | if (!_fileOs) { |
| 319 | LOGE("error cannot open file: %s", path); |
| 320 | return 0; |
| 321 | } |
| 322 |
| 323 | inopt.rate = rate; |
| 324 | inopt.gain = 0; |
| 325 | inopt.endianness = 0; |
| 326 | inopt.copy_comments = 0; |
| 327 | inopt.rawmode = 0; |
| 328 | inopt.ignorelength = 0; |
| 329 | inopt.samplesize = 16; |
| 330 | inopt.channels = 1; |
| 331 | inopt.skip = 0; |
| 332 |
| 333 | comment_init(&inopt.comments, &inopt.comments_length, opus_get_version_string()); |
| 334 |
| 335 | if (rate != coding_rate) { |
| 336 | LOGE("Invalid rate"); |
| 337 | return 0; |
| 338 | } |
| 339 |
| 340 | header.channels = 1; |
| 341 | header.channel_mapping = 0; |
| 342 | header.input_sample_rate = rate; |
| 343 | header.gain = inopt.gain; |
| 344 | header.nb_streams = 1; |
| 345 |
| 346 | int result = OPUS_OK; |
| 347 | _encoder = opus_encoder_create(coding_rate, 1, opus_application, &result); |
| 348 | if (result != OPUS_OK) { |
| 349 | LOGE("Error cannot create encoder: %s", opus_strerror(result)); |
| 350 | return 0; |
| 351 | } |
| 352 |
| 353 | min_bytes = max_frame_bytes = (1275 * 3 + 7) * header.nb_streams; |
| 354 | _packet = malloc(max_frame_bytes); |
| 355 |
| 356 | result = opus_encoder_ctl(_encoder, OPUS_SET_BITRATE(bitrate)); |
| 357 | //result = opus_encoder_ctl(_encoder, OPUS_SET_COMPLEXITY(10)); |
| 358 | if (result != OPUS_OK) { |
| 359 | LOGE("Error OPUS_SET_BITRATE returned: %s", opus_strerror(result)); |
| 360 | return 0; |
| 361 | } |
| 362 |
| 363 | #ifdef OPUS_SET_LSB_DEPTH |
| 364 | result = opus_encoder_ctl(_encoder, OPUS_SET_LSB_DEPTH(MAX(8, MIN(24, inopt.samplesize)))); |
| 365 | if (result != OPUS_OK) { |
| 366 | LOGE("Warning OPUS_SET_LSB_DEPTH returned: %s", opus_strerror(result)); |
| 367 | } |
| 368 | #endif |
| 369 |
| 370 | opus_int32 lookahead; |
| 371 | result = opus_encoder_ctl(_encoder, OPUS_GET_LOOKAHEAD(&lookahead)); |
| 372 | if (result != OPUS_OK) { |
| 373 | LOGE("Error OPUS_GET_LOOKAHEAD returned: %s", opus_strerror(result)); |
| 374 | return 0; |
| 375 | } |
| 376 |
| 377 | inopt.skip += lookahead; |
| 378 | header.preskip = (int)(inopt.skip * (48000.0 / coding_rate)); |
| 379 | inopt.extraout = (int)(header.preskip * (rate / 48000.0)); |
| 380 |
| 381 | if (ogg_stream_init(&os, serialno = rand()) == -1) { |
| 382 | LOGE("Error: stream init failed"); |
| 383 | return 0; |
| 384 | } |
| 385 |
| 386 | unsigned char header_data[100]; |
| 387 | int packet_size = opus_header_to_packet(&header, header_data, 100); |
| 388 | op.packet = header_data; |
| 389 | op.bytes = packet_size; |
| 390 | op.b_o_s = 1; |
| 391 | op.e_o_s = 0; |
| 392 | op.granulepos = 0; |
| 393 | op.packetno = 0; |
| 394 | ogg_stream_packetin(&os, &op); |
| 395 |
| 396 | while ((result = ogg_stream_flush(&os, &og))) { |
| 397 | if (!result) { |
| 398 | break; |
| 399 | } |
| 400 |
| 401 | int pageBytesWritten = writeOggPage(&og, _fileOs); |
| 402 | if (pageBytesWritten != og.header_len + og.body_len) { |
| 403 | LOGE("Error: failed writing header to output stream"); |
| 404 | return 0; |
| 405 | } |
| 406 | bytes_written += pageBytesWritten; |
| 407 | pages_out++; |
| 408 | } |
| 409 |
| 410 | comment_pad(&inopt.comments, &inopt.comments_length, comment_padding); |
| 411 | op.packet = (unsigned char *)inopt.comments; |
| 412 | op.bytes = inopt.comments_length; |
| 413 | op.b_o_s = 0; |
| 414 | op.e_o_s = 0; |
| 415 | op.granulepos = 0; |
| 416 | op.packetno = 1; |
| 417 | ogg_stream_packetin(&os, &op); |
| 418 |
| 419 | while ((result = ogg_stream_flush(&os, &og))) { |
| 420 | if (result == 0) { |
| 421 | break; |
| 422 | } |
| 423 |
| 424 | int writtenPageBytes = writeOggPage(&og, _fileOs); |
| 425 | if (writtenPageBytes != og.header_len + og.body_len) { |
| 426 | LOGE("Error: failed writing header to output stream"); |
| 427 | return 0; |
| 428 | } |
| 429 |
| 430 | bytes_written += writtenPageBytes; |
| 431 | pages_out++; |
| 432 | } |
| 433 |
| 434 | free(inopt.comments); |
| 435 |
| 436 | return 1; |
| 437 | } |
| 438 |
| 439 | int writeFrame(uint8_t *framePcmBytes, uint32_t frameByteCount, int end) { |
| 440 | size_t cur_frame_size = frame_size; |
| 441 | _packetId++; |
| 442 |
| 443 | opus_int32 nb_samples = frameByteCount / 2; |
| 444 | total_samples += nb_samples; |
| 445 | op.e_o_s = end; |
| 446 |
| 447 | int nbBytes = 0; |
| 448 |
| 449 | if (nb_samples != 0) { |
| 450 | uint8_t *paddedFrameBytes = framePcmBytes; |
| 451 | int freePaddedFrameBytes = 0; |
| 452 |
| 453 | if (nb_samples < cur_frame_size) { |
| 454 | paddedFrameBytes = malloc(cur_frame_size * 2); |
| 455 | freePaddedFrameBytes = 1; |
| 456 | memcpy(paddedFrameBytes, framePcmBytes, frameByteCount); |
| 457 | memset(paddedFrameBytes + nb_samples * 2, 0, cur_frame_size * 2 - nb_samples * 2); |
| 458 | } |
| 459 |
| 460 | nbBytes = opus_encode(_encoder, (opus_int16 *)paddedFrameBytes, cur_frame_size, _packet, max_frame_bytes / 10); |
| 461 | if (freePaddedFrameBytes) { |
| 462 | free(paddedFrameBytes); |
| 463 | } |
| 464 |
| 465 | if (nbBytes < 0) { |
| 466 | LOGE("Encoding failed: %s. Aborting.", opus_strerror(nbBytes)); |
| 467 | return 0; |
| 468 | } |
| 469 |
| 470 | enc_granulepos += cur_frame_size * 48000 / coding_rate; |
| 471 | size_segments = (nbBytes + 255) / 255; |
| 472 | min_bytes = MIN(nbBytes, min_bytes); |
| 473 | } |
| 474 |
| 475 | while ((((size_segments <= 255) && (last_segments + size_segments > 255)) || (enc_granulepos - last_granulepos > max_ogg_delay)) && ogg_stream_flush_fill(&os, &og, 255 * 255)) { |
| 476 | if (ogg_page_packets(&og) != 0) { |
| 477 | last_granulepos = ogg_page_granulepos(&og); |
| 478 | } |
| 479 |
| 480 | last_segments -= og.header[26]; |
| 481 | int writtenPageBytes = writeOggPage(&og, _fileOs); |
| 482 | if (writtenPageBytes != og.header_len + og.body_len) { |
| 483 | LOGE("Error: failed writing data to output stream"); |
| 484 | return 0; |
| 485 | } |
| 486 | bytes_written += writtenPageBytes; |
| 487 | pages_out++; |
| 488 | } |
| 489 |
| 490 | op.packet = _packet; |
| 491 | op.bytes = nbBytes; |
| 492 | op.b_o_s = 0; |
| 493 | op.granulepos = enc_granulepos; |
| 494 | if (op.e_o_s) { |
| 495 | op.granulepos = ((total_samples * 48000 + rate - 1) / rate) + header.preskip; |
| 496 | } |
| 497 | op.packetno = 2 + _packetId; |
| 498 | ogg_stream_packetin(&os, &op); |
| 499 | last_segments += size_segments; |
| 500 |
| 501 | while ((op.e_o_s || (enc_granulepos + (frame_size * 48000 / coding_rate) - last_granulepos > max_ogg_delay) || (last_segments >= 255)) ? ogg_stream_flush_fill(&os, &og, 255 * 255) : ogg_stream_pageout_fill(&os, &og, 255 * 255)) { |
| 502 | if (ogg_page_packets(&og) != 0) { |
| 503 | last_granulepos = ogg_page_granulepos(&og); |
| 504 | } |
| 505 | last_segments -= og.header[26]; |
| 506 | int writtenPageBytes = writeOggPage(&og, _fileOs); |
| 507 | if (writtenPageBytes != og.header_len + og.body_len) { |
| 508 | LOGE("Error: failed writing data to output stream"); |
| 509 | return 0; |
| 510 | } |
| 511 | bytes_written += writtenPageBytes; |
| 512 | pages_out++; |
| 513 | } |
| 514 |
| 515 | return 1; |
| 516 | } |
| 517 |
| 518 | JNIEXPORT jint Java_org_telegram_messenger_MediaController_startRecord(JNIEnv *env, jclass class, jstring path, jint sampleRate) { |
| 519 | const char *pathStr = (*env)->GetStringUTFChars(env, path, 0); |
| 520 |
| 521 | int32_t result = initRecorder(pathStr, sampleRate); |
| 522 |
| 523 | if (pathStr != 0) { |
| 524 | (*env)->ReleaseStringUTFChars(env, path, pathStr); |
| 525 | } |
| 526 |
| 527 | return result; |
| 528 | } |
| 529 |
| 530 | JNIEXPORT jint Java_org_telegram_messenger_MediaController_writeFrame(JNIEnv *env, jclass class, jobject frame, jint len) { |
| 531 | jbyte *frameBytes = (*env)->GetDirectBufferAddress(env, frame); |
| 532 | return writeFrame((uint8_t *) frameBytes, (uint32_t) len, len / 2 < frame_size); |
| 533 | } |
| 534 |
| 535 | JNIEXPORT void Java_org_telegram_messenger_MediaController_stopRecord(JNIEnv *env, jclass class) { |
| 536 | cleanupRecorder(); |
| 537 | } |
| 538 |
| 539 | JNIEXPORT jint Java_org_telegram_messenger_MediaController_isOpusFile(JNIEnv *env, jclass class, jstring path) { |
| 540 | const char *pathStr = (*env)->GetStringUTFChars(env, path, 0); |
| 541 |
| 542 | int32_t result = 0; |
| 543 |
| 544 | int32_t error = OPUS_OK; |
| 545 | OggOpusFile *file = op_test_file(pathStr, &error); |
| 546 | if (file != NULL) { |
| 547 | error = op_test_open(file); |
| 548 | op_free(file); |
| 549 | result = error == OPUS_OK; |
| 550 | } |
| 551 |
| 552 | if (pathStr != 0) { |
| 553 | (*env)->ReleaseStringUTFChars(env, path, pathStr); |
| 554 | } |
| 555 |
| 556 | return result; |
| 557 | } |
| 558 |
| 559 | static inline void set_bits(uint8_t *bytes, int32_t bitOffset, int32_t value) { |
| 560 | bytes += bitOffset / 8; |
| 561 | bitOffset %= 8; |
| 562 |
| 563 | uint16_t bits = (uint16_t) (value << bitOffset); |
| 564 | bytes[0] |= (uint8_t) bits; |
| 565 | bytes[1] |= (uint8_t) (bits >> 8); |
| 566 | } |
| 567 |
| 568 | JNIEXPORT jbyteArray Java_org_telegram_messenger_MediaController_getWaveform2(JNIEnv *env, jclass class, jshortArray array, jint length) { |
| 569 |
| 570 | jshort *sampleBuffer = (*env)->GetShortArrayElements(env, array, 0); |
| 571 | if (sampleBuffer == NULL) { |
| 572 | return NULL; |
| 573 | } |
| 574 |
| 575 | const int32_t resultSamples = 100; |
| 576 | uint16_t *samples = calloc(resultSamples, sizeof(uint16_t)); |
| 577 | if (samples == NULL) { |
| 578 | (*env)->ReleaseShortArrayElements(env, array, sampleBuffer, JNI_ABORT); |
| 579 | return NULL; |
| 580 | } |
| 581 | uint64_t sampleIndex = 0; |
| 582 | uint16_t peakSample = 0; |
| 583 | int32_t sampleRate = (int32_t) MAX(1, length / resultSamples); |
| 584 | int32_t index = 0; |
| 585 |
| 586 | for (int32_t i = 0; i < length; i++) { |
| 587 | uint16_t sample = (uint16_t) abs(sampleBuffer[i]); |
| 588 | if (sample > peakSample) { |
| 589 | peakSample = sample; |
| 590 | } |
| 591 | if (sampleIndex++ % sampleRate == 0) { |
| 592 | if (index < resultSamples) { |
| 593 | samples[index++] = peakSample; |
| 594 | } |
| 595 | peakSample = 0; |
| 596 | } |
| 597 | } |
| 598 |
| 599 | int64_t sumSamples = 0; |
| 600 | for (int32_t i = 0; i < resultSamples; i++) { |
| 601 | sumSamples += samples[i]; |
| 602 | } |
| 603 | uint16_t peak = (uint16_t) (sumSamples * 1.8f / resultSamples); |
| 604 | if (peak < 2500) { |
| 605 | peak = 2500; |
| 606 | } |
| 607 |
| 608 | for (int32_t i = 0; i < resultSamples; i++) { |
| 609 | uint16_t sample = (uint16_t) ((int64_t) samples[i]); |
| 610 | if (sample > peak) { |
| 611 | samples[i] = peak; |
| 612 | } |
| 613 | } |
| 614 |
| 615 | (*env)->ReleaseShortArrayElements(env, array, sampleBuffer, JNI_ABORT); |
| 616 |
| 617 | uint32_t bitstreamLength = resultSamples * 5 / 8 + 1; |
| 618 | jbyteArray result = (*env)->NewByteArray(env, bitstreamLength); |
| 619 | if (result) { |
| 620 | uint8_t *bytes = calloc(bitstreamLength + 4, 1); |
| 621 | if (bytes != NULL) { |
| 622 | for (int32_t i = 0; i < resultSamples; i++) { |
| 623 | int32_t value = MIN(31, abs((int32_t) samples[i]) * 31 / peak); |
| 624 | set_bits(bytes, i * 5, value & 31); |
| 625 | } |
| 626 | (*env)->SetByteArrayRegion(env, result, 0, bitstreamLength, (jbyte *) bytes); |
| 627 | free(bytes); |
| 628 | } else { |
| 629 | result = NULL; |
| 630 | } |
| 631 | } |
| 632 | free(samples); |
| 633 |
| 634 | return result; |
| 635 | } |
| 636 |
| 637 | int16_t *sampleBuffer = NULL; |
| 638 |
| 639 | JNIEXPORT jbyteArray Java_org_telegram_messenger_MediaController_getWaveform(JNIEnv *env, jclass class, jstring path) { |
| 640 | const char *pathStr = (*env)->GetStringUTFChars(env, path, 0); |
| 641 | if (pathStr == NULL) { |
| 642 | return NULL; |
| 643 | } |
| 644 | jbyteArray result = 0; |
| 645 |
| 646 | int error = OPUS_OK; |
| 647 | OggOpusFile *opusFile = op_open_file(pathStr, &error); |
| 648 | if (opusFile != NULL && error == OPUS_OK) { |
| 649 | int64_t totalSamples = op_pcm_total(opusFile, -1); |
| 650 | const uint32_t resultSamples = 100; |
| 651 | int32_t sampleRate = MAX(1, (int32_t) (totalSamples / resultSamples)); |
| 652 |
| 653 | uint16_t *samples = calloc(resultSamples, sizeof(uint16_t)); |
| 654 |
| 655 | size_t bufferSize = 1024 * 128; |
| 656 | if (sampleBuffer == NULL) { |
| 657 | sampleBuffer = malloc(bufferSize); |
| 658 | } |
| 659 |
| 660 | if (samples != NULL && sampleBuffer != NULL) { |
| 661 | uint64_t sampleIndex = 0; |
| 662 | uint16_t peakSample = 0; |
| 663 |
| 664 | int32_t index = 0; |
| 665 | int decodeFailed = 0; |
| 666 |
| 667 | while (1) { |
| 668 | int readSamples = op_read(opusFile, sampleBuffer, bufferSize / 2, NULL); |
| 669 | if (readSamples < 0) { |
| 670 | LOGE("getWaveform: op_read failed: %d", readSamples); |
| 671 | decodeFailed = 1; |
| 672 | break; |
| 673 | } |
| 674 | if (readSamples == 0) { |
| 675 | break; |
| 676 | } |
| 677 | for (int32_t i = 0; i < readSamples; i++) { |
| 678 | uint16_t sample = (uint16_t) abs(sampleBuffer[i]); |
| 679 | if (sample > peakSample) { |
| 680 | peakSample = sample; |
| 681 | } |
| 682 | if (sampleIndex++ % sampleRate == 0) { |
| 683 | if (index < resultSamples) { |
| 684 | samples[index++] = peakSample; |
| 685 | } |
| 686 | peakSample = 0; |
| 687 | } |
| 688 | } |
| 689 | } |
| 690 |
| 691 | if (!decodeFailed) { |
| 692 | int64_t sumSamples = 0; |
| 693 | for (int32_t i = 0; i < resultSamples; i++) { |
| 694 | sumSamples += samples[i]; |
| 695 | } |
| 696 | uint16_t peak = (uint16_t) (sumSamples * 1.8f / resultSamples); |
| 697 | if (peak < 2500) { |
| 698 | peak = 2500; |
| 699 | } |
| 700 |
| 701 | for (int32_t i = 0; i < resultSamples; i++) { |
| 702 | uint16_t sample = (uint16_t) ((int64_t) samples[i]); |
| 703 | if (sample > peak) { |
| 704 | samples[i] = peak; |
| 705 | } |
| 706 | } |
| 707 |
| 708 | uint32_t bitstreamLength = (resultSamples * 5) / 8 + 1; |
| 709 | result = (*env)->NewByteArray(env, bitstreamLength); |
| 710 | if (result) { |
| 711 | uint8_t *bytes = calloc(bitstreamLength + 4, 1); |
| 712 | if (bytes != NULL) { |
| 713 | for (int32_t i = 0; i < resultSamples; i++) { |
| 714 | int32_t value = MIN(31, abs((int32_t) samples[i]) * 31 / peak); |
| 715 | set_bits(bytes, i * 5, value & 31); |
| 716 | } |
| 717 |
| 718 | (*env)->SetByteArrayRegion(env, result, 0, bitstreamLength, (jbyte *) bytes); |
| 719 | free(bytes); |
| 720 | } else { |
| 721 | result = NULL; |
| 722 | } |
| 723 | } |
| 724 | } |
| 725 | } |
| 726 |
| 727 | free(samples); |
| 728 | op_free(opusFile); |
| 729 | } |
| 730 |
| 731 | (*env)->ReleaseStringUTFChars(env, path, pathStr); |
| 732 | return result; |
| 733 | } |
| 734 |
| 735 | JNIEXPORT void JNICALL Java_org_telegram_ui_Stories_recorder_FfmpegAudioWaveformLoader_init(JNIEnv *env, jobject obj, jstring pathJStr, jint count) { |
| 736 | const char *path = (*env)->GetStringUTFChars(env, pathJStr, 0); |
| 737 | if (path == NULL) { |
| 738 | return; |
| 739 | } |
| 740 | if (count <= 0) { |
| 741 | (*env)->ReleaseStringUTFChars(env, pathJStr, path); |
| 742 | return; |
| 743 | } |
| 744 |
| 745 | AVFormatContext *formatContext = avformat_alloc_context(); |
| 746 | if (!formatContext) { |
| 747 | (*env)->ReleaseStringUTFChars(env, pathJStr, path); |
| 748 | return; |
| 749 | } |
| 750 |
| 751 | int res; |
| 752 | if ((res = avformat_open_input(&formatContext, path, NULL, NULL)) != 0) { |
| 753 | LOGD("avformat_open_input error %s", av_err2str(res)); |
| 754 | avformat_free_context(formatContext); |
| 755 | (*env)->ReleaseStringUTFChars(env, pathJStr, path); |
| 756 | return; |
| 757 | } |
| 758 |
| 759 | if (avformat_find_stream_info(formatContext, NULL) < 0) { |
| 760 | avformat_close_input(&formatContext); |
| 761 | (*env)->ReleaseStringUTFChars(env, pathJStr, path); |
| 762 | return; |
| 763 | } |
| 764 |
| 765 | AVCodec *codec = NULL; |
| 766 | int audioStreamIndex = av_find_best_stream(formatContext, AVMEDIA_TYPE_AUDIO, -1, -1, &codec, 0); |
| 767 | if (audioStreamIndex < 0 || codec == NULL) { |
| 768 | LOGD("av_find_best_stream error %s", av_err2str(audioStreamIndex)); |
| 769 | avformat_close_input(&formatContext); |
| 770 | (*env)->ReleaseStringUTFChars(env, pathJStr, path); |
| 771 | return; |
| 772 | } |
| 773 |
| 774 | AVCodecContext *codecContext = avcodec_alloc_context3(codec); |
| 775 | if (codecContext == NULL) { |
| 776 | avformat_close_input(&formatContext); |
| 777 | (*env)->ReleaseStringUTFChars(env, pathJStr, path); |
| 778 | return; |
| 779 | } |
| 780 | if (avcodec_parameters_to_context(codecContext, formatContext->streams[audioStreamIndex]->codecpar) < 0) { |
| 781 | avcodec_free_context(&codecContext); |
| 782 | avformat_close_input(&formatContext); |
| 783 | (*env)->ReleaseStringUTFChars(env, pathJStr, path); |
| 784 | return; |
| 785 | } |
| 786 |
| 787 | int64_t duration_in_microseconds = formatContext->duration; |
| 788 | double duration_in_seconds = (double)duration_in_microseconds / AV_TIME_BASE; |
| 789 |
| 790 | if (avcodec_open2(codecContext, codec, NULL) < 0) { |
| 791 | avcodec_free_context(&codecContext); |
| 792 | avformat_close_input(&formatContext); |
| 793 | (*env)->ReleaseStringUTFChars(env, pathJStr, path); |
| 794 | return; |
| 795 | } |
| 796 |
| 797 | jclass cls = (*env)->GetObjectClass(env, obj); |
| 798 | jmethodID mid = (*env)->GetMethodID(env, cls, "receiveChunk", "([SI)V"); |
| 799 |
| 800 | AVFrame *frame = av_frame_alloc(); |
| 801 | if (frame == NULL) { |
| 802 | avcodec_free_context(&codecContext); |
| 803 | avformat_close_input(&formatContext); |
| 804 | (*env)->ReleaseStringUTFChars(env, pathJStr, path); |
| 805 | return; |
| 806 | } |
| 807 | AVPacket packet; |
| 808 |
| 809 | int sampleRate = codecContext->sample_rate; |
| 810 | int skip = 4; |
| 811 | int barWidth = (int) round((double) duration_in_seconds * sampleRate / count / (1 + skip)); |
| 812 |
| 813 | int channels = codecContext->ch_layout.nb_channels; |
| 814 | if (channels <= 0) { |
| 815 | av_frame_free(&frame); |
| 816 | avcodec_free_context(&codecContext); |
| 817 | avformat_close_input(&formatContext); |
| 818 | (*env)->ReleaseStringUTFChars(env, pathJStr, path); |
| 819 | return; |
| 820 | } |
| 821 |
| 822 | short peak = 0; |
| 823 | int currentCount = 0; |
| 824 | int index = 0; |
| 825 | int chunkIndex = 0; |
| 826 | short waveformChunkData[32] = {0}; |
| 827 |
| 828 | while (av_read_frame(formatContext, &packet) >= 0) { |
| 829 | if (packet.stream_index == audioStreamIndex) { |
| 830 | int response = avcodec_send_packet(codecContext, &packet); |
| 831 |
| 832 | while (response >= 0) { |
| 833 | response = avcodec_receive_frame(codecContext, frame); |
| 834 | if (response == AVERROR(EAGAIN) || response == AVERROR_EOF) { |
| 835 | break; |
| 836 | } else if (response < 0) { |
| 837 | break; |
| 838 | } |
| 839 |
| 840 | const int is_planar = av_sample_fmt_is_planar(codecContext->sample_fmt); |
| 841 | const int sample_size = av_get_bytes_per_sample(codecContext->sample_fmt); |
| 842 | for (int i = 0; i < frame->nb_samples; i++) { |
| 843 | int sum = 0; |
| 844 | for (int channel = 0; channel < channels; channel++) { |
| 845 | uint8_t *data; |
| 846 | if (is_planar) { |
| 847 | data = frame->data[channel] + i * sample_size; |
| 848 | } else { |
| 849 | data = frame->data[0] + (i * channels + channel) * sample_size; |
| 850 | } |
| 851 | short sample_value = 0; |
| 852 | switch (codecContext->sample_fmt) { |
| 853 | case AV_SAMPLE_FMT_S16: |
| 854 | case AV_SAMPLE_FMT_S16P: |
| 855 | sample_value = *(int16_t *)data; |
| 856 | break; |
| 857 |
| 858 | case AV_SAMPLE_FMT_FLT: |
| 859 | case AV_SAMPLE_FMT_FLTP: |
| 860 | sample_value = (short)(*(float *)data * 32767.0f); |
| 861 | break; |
| 862 |
| 863 | case AV_SAMPLE_FMT_U8: |
| 864 | case AV_SAMPLE_FMT_U8P: |
| 865 | sample_value = (*(uint8_t *)data - 128) * 256; |
| 866 | break; |
| 867 |
| 868 | default: |
| 869 | break; |
| 870 | } |
| 871 | sum += sample_value; |
| 872 | } |
| 873 | short value = sum / channels; |
| 874 |
| 875 | if (currentCount >= barWidth) { |
| 876 | waveformChunkData[index - chunkIndex] = peak; |
| 877 | index++; |
| 878 | if (index - chunkIndex >= sizeof(waveformChunkData) / sizeof(short) || index >= count) { |
| 879 | jshortArray waveformData = (*env)->NewShortArray(env, sizeof(waveformChunkData) / sizeof(short)); |
| 880 | if (waveformData == NULL) { |
| 881 | break; |
| 882 | } |
| 883 | (*env)->SetShortArrayRegion(env, waveformData, 0, sizeof(waveformChunkData) / sizeof(short), waveformChunkData); |
| 884 | (*env)->CallVoidMethod(env, obj, mid, waveformData, sizeof(waveformChunkData) / sizeof(short)); |
| 885 |
| 886 | memset(waveformChunkData, 0, sizeof(waveformChunkData)); |
| 887 | chunkIndex = index; |
| 888 |
| 889 | (*env)->DeleteLocalRef(env, waveformData); |
| 890 | } |
| 891 | peak = 0; |
| 892 | currentCount = 0; |
| 893 | if (index >= count) { |
| 894 | break; |
| 895 | } |
| 896 | } |
| 897 |
| 898 | if (peak < value) { |
| 899 | peak = value; |
| 900 | } |
| 901 | currentCount++; |
| 902 |
| 903 | i += skip; |
| 904 | if (i >= frame->nb_samples) { |
| 905 | break; |
| 906 | } |
| 907 | } |
| 908 | } |
| 909 | } |
| 910 |
| 911 | av_packet_unref(&packet); |
| 912 |
| 913 | if (index >= count) { |
| 914 | break; |
| 915 | } |
| 916 |
| 917 | jfieldID fid = (*env)->GetFieldID(env, cls, "running", "Z"); |
| 918 | jboolean running = (*env)->GetBooleanField(env, obj, fid); |
| 919 | if (running == JNI_FALSE) { |
| 920 | break; |
| 921 | } |
| 922 | } |
| 923 |
| 924 | av_frame_free(&frame); |
| 925 | avcodec_free_context(&codecContext); |
| 926 | avformat_close_input(&formatContext); |
| 927 |
| 928 | (*env)->ReleaseStringUTFChars(env, pathJStr, path); |
| 929 | } |
| 930 |
| 931 | int cropOpusAudio(const char *inputPath, const char *outputPath, float startTimeMs, float endTimeMs) { |
| 932 | int error; |
| 933 | OggOpusFile *opusFile = op_open_file(inputPath, &error); |
| 934 | if (!opusFile || error != OPUS_OK) { |
| 935 | LOGE("Failed to open input opus file: %s", opus_strerror(error)); |
| 936 | return 0; |
| 937 | } |
| 938 |
| 939 | const OpusHead *head = op_head(opusFile, -1); |
| 940 | if (!head) { |
| 941 | LOGE("Failed to read Opus header"); |
| 942 | op_free(opusFile); |
| 943 | return 0; |
| 944 | } |
| 945 |
| 946 | int channels = head->channel_count; |
| 947 | opus_int64 total_source_samples = op_pcm_total(opusFile, -1); |
| 948 | if (total_source_samples < 0) { |
| 949 | LOGE("Failed to get source sample count: %lld", (long long) total_source_samples); |
| 950 | op_free(opusFile); |
| 951 | return 0; |
| 952 | } |
| 953 |
| 954 | opus_int32 rate = 48000; |
| 955 |
| 956 | opus_int64 start_sample = MAX(0, MIN(total_source_samples, (opus_int64) ((startTimeMs / 1000.0) * rate))); |
| 957 | opus_int64 end_sample = MAX(0, MIN(total_source_samples, (opus_int64) ((endTimeMs / 1000.0) * rate))); |
| 958 | opus_int64 crop_length = end_sample - start_sample; |
| 959 |
| 960 | if (start_sample >= total_source_samples || end_sample > total_source_samples || start_sample >= end_sample) { |
| 961 | LOGE("Invalid crop range"); |
| 962 | op_free(opusFile); |
| 963 | return 0; |
| 964 | } |
| 965 |
| 966 | if (op_pcm_seek(opusFile, start_sample) != 0) { |
| 967 | LOGE("Failed to seek to start sample"); |
| 968 | op_free(opusFile); |
| 969 | return 0; |
| 970 | } |
| 971 |
| 972 | if (!initRecorder(outputPath, rate)) { |
| 973 | LOGE("Failed to init recorder"); |
| 974 | op_free(opusFile); |
| 975 | return 0; |
| 976 | } |
| 977 |
| 978 | int16_t *buffer = malloc(sizeof(int16_t) * frame_size * channels); |
| 979 | if (!buffer) { |
| 980 | LOGE("Out of memory"); |
| 981 | cleanupRecorder(); |
| 982 | op_free(opusFile); |
| 983 | return 0; |
| 984 | } |
| 985 |
| 986 | int success = 1; |
| 987 | opus_int64 remaining_samples = crop_length; |
| 988 | while (remaining_samples > 0) { |
| 989 | int max_samples = (int) MIN(960, remaining_samples / channels); |
| 990 | if (max_samples <= 0) { |
| 991 | break; |
| 992 | } |
| 993 | int samples_read = op_read(opusFile, buffer, max_samples * channels, NULL); |
| 994 | if (samples_read < 0) { |
| 995 | LOGE("Decoding error from op_read(): %d", samples_read); |
| 996 | success = 0; |
| 997 | break; |
| 998 | } |
| 999 | if (samples_read == 0) { |
| 1000 | break; |
| 1001 | } |
| 1002 | remaining_samples -= samples_read; |
| 1003 |
| 1004 | int end = remaining_samples <= 0; |
| 1005 |
| 1006 | size_t byte_count = samples_read * sizeof(int16_t); |
| 1007 | if (!writeFrame((uint8_t *)buffer, byte_count, end)) { |
| 1008 | LOGE("Failed to write frame"); |
| 1009 | success = 0; |
| 1010 | break; |
| 1011 | } |
| 1012 | } |
| 1013 |
| 1014 | free(buffer); |
| 1015 | cleanupRecorder(); |
| 1016 | op_free(opusFile); |
| 1017 |
| 1018 | return success; |
| 1019 | } |
| 1020 |
| 1021 | int append_stream(OggOpusFile *of, int16_t* buffer, int channels, int is_last) { |
| 1022 | opus_int64 total_source_samples = op_pcm_total(of, -1); |
| 1023 | if (total_source_samples < 0) { |
| 1024 | LOGE("Failed to get source sample count: %lld",(long long) total_source_samples); |
| 1025 | return 0; |
| 1026 | } |
| 1027 |
| 1028 | while (total_source_samples > 0) { |
| 1029 | int samples_read = op_read(of, buffer, frame_size, NULL); |
| 1030 | if (samples_read < 0) { |
| 1031 | LOGE("Decoding error from op_read(): %d", samples_read); |
| 1032 | return 0; |
| 1033 | } |
| 1034 | if (samples_read == 0) { |
| 1035 | break; |
| 1036 | } |
| 1037 | total_source_samples -= samples_read; |
| 1038 | size_t byte_count = (size_t) samples_read * channels * sizeof(int16_t); |
| 1039 | if (!writeFrame((uint8_t*) buffer, byte_count, is_last && total_source_samples <= 0)) { |
| 1040 | LOGE("Failed to write encoded frame"); |
| 1041 | return 0; |
| 1042 | } |
| 1043 | } |
| 1044 | return 1; |
| 1045 | } |
| 1046 |
| 1047 | int joinOpusAudios(const char* file1, const char* file2, const char* dest) { |
| 1048 | int error; |
| 1049 | OggOpusFile *opusFile1 = op_open_file(file1, &error); |
| 1050 | if (!opusFile1 || error != OPUS_OK) { |
| 1051 | LOGE("Failed to open input opus file1: %s", opus_strerror(error)); |
| 1052 | return 0; |
| 1053 | } |
| 1054 | OggOpusFile *opusFile2 = op_open_file(file2, &error); |
| 1055 | if (!opusFile2 || error != OPUS_OK) { |
| 1056 | LOGE("Failed to open input opus file2: %s", opus_strerror(error)); |
| 1057 | if (opusFile2 != NULL) { |
| 1058 | op_free(opusFile2); |
| 1059 | } |
| 1060 | op_free(opusFile1); |
| 1061 | return 0; |
| 1062 | } |
| 1063 |
| 1064 | const OpusHead *head1 = op_head(opusFile1, -1); |
| 1065 | if (!head1) { |
| 1066 | LOGE("Failed to read Opus header"); |
| 1067 | op_free(opusFile1); |
| 1068 | op_free(opusFile2); |
| 1069 | return 0; |
| 1070 | } |
| 1071 | const OpusHead *head2 = op_head(opusFile2, -1); |
| 1072 | if (!head2) { |
| 1073 | LOGE("Failed to read Opus header"); |
| 1074 | op_free(opusFile1); |
| 1075 | op_free(opusFile2); |
| 1076 | return 0; |
| 1077 | } |
| 1078 |
| 1079 | int channels = MIN(head1->channel_count, head2->channel_count); |
| 1080 | opus_int32 rate = 48000; |
| 1081 |
| 1082 | if (!initRecorder(dest, rate)) { |
| 1083 | LOGE("Failed to init recorder"); |
| 1084 | op_free(opusFile1); |
| 1085 | op_free(opusFile2); |
| 1086 | return 0; |
| 1087 | } |
| 1088 |
| 1089 | int16_t *buffer = malloc(sizeof(int16_t) * frame_size * channels); |
| 1090 | if (!buffer) { |
| 1091 | LOGE("Out of memory"); |
| 1092 | cleanupRecorder(); |
| 1093 | op_free(opusFile1); |
| 1094 | op_free(opusFile2); |
| 1095 | return 0; |
| 1096 | } |
| 1097 |
| 1098 | int success = append_stream(opusFile1, buffer, channels, 0); |
| 1099 | if (success) { |
| 1100 | success = append_stream(opusFile2, buffer, channels, 1); |
| 1101 | } |
| 1102 |
| 1103 | free(buffer); |
| 1104 | cleanupRecorder(); |
| 1105 | op_free(opusFile1); |
| 1106 | op_free(opusFile2); |
| 1107 |
| 1108 | return success; |
| 1109 | } |
| 1110 |
| 1111 | JNIEXPORT jboolean Java_org_telegram_messenger_MediaController_cropOpusFile(JNIEnv *env, jclass class, jstring src, jstring dst, jlong startMs, jlong endMs) { |
| 1112 | const char* srcStr = (*env)->GetStringUTFChars(env, src, 0); |
| 1113 | const char* dstStr = (*env)->GetStringUTFChars(env, dst, 0); |
| 1114 | int result = cropOpusAudio(srcStr, dstStr, startMs, endMs); |
| 1115 | (*env)->ReleaseStringUTFChars(env, src, srcStr); |
| 1116 | (*env)->ReleaseStringUTFChars(env, dst, dstStr); |
| 1117 | return result == 1; |
| 1118 | } |
| 1119 |
| 1120 | JNIEXPORT jboolean Java_org_telegram_messenger_MediaController_joinOpusFiles(JNIEnv* env, jclass class, jstring file1, jstring file2, jstring dest) { |
| 1121 | const char* file1Str = (*env)->GetStringUTFChars(env, file1, 0); |
| 1122 | const char* file2Str = (*env)->GetStringUTFChars(env, file2, 0); |
| 1123 | const char* destStr = (*env)->GetStringUTFChars(env, dest, 0); |
| 1124 | int result = joinOpusAudios(file1Str, file2Str, destStr); |
| 1125 | (*env)->ReleaseStringUTFChars(env, file1, file1Str); |
| 1126 | (*env)->ReleaseStringUTFChars(env, file2, file2Str); |
| 1127 | (*env)->ReleaseStringUTFChars(env, dest, destStr); |
| 1128 | return result == 1; |
| 1129 | } |
| 1130 |
| 1131 | #include <stdint.h> |
| 1132 |
| 1133 | typedef struct { |
| 1134 | DenoiseState *state; |
| 1135 | float *input; |
| 1136 | float *output; |
| 1137 | int frame_size; |
| 1138 | } AudioNoiseSuppressorContext; |
| 1139 |
| 1140 | static void destroyAudioNoiseSuppressorContext(AudioNoiseSuppressorContext *context) { |
| 1141 | if (!context) { |
| 1142 | return; |
| 1143 | } |
| 1144 | if (context->state) { |
| 1145 | rnnoise_destroy(context->state); |
| 1146 | } |
| 1147 | free(context->input); |
| 1148 | free(context->output); |
| 1149 | free(context); |
| 1150 | } |
| 1151 |
| 1152 | static AudioNoiseSuppressorContext *createAudioNoiseSuppressorContext() { |
| 1153 | AudioNoiseSuppressorContext *context = calloc(1, sizeof(AudioNoiseSuppressorContext)); |
| 1154 | if (!context) { |
| 1155 | return NULL; |
| 1156 | } |
| 1157 | context->frame_size = rnnoise_get_frame_size(); |
| 1158 | if (context->frame_size <= 0) { |
| 1159 | destroyAudioNoiseSuppressorContext(context); |
| 1160 | return NULL; |
| 1161 | } |
| 1162 | context->input = malloc(sizeof(float) * context->frame_size); |
| 1163 | context->output = malloc(sizeof(float) * context->frame_size); |
| 1164 | context->state = rnnoise_create(NULL); |
| 1165 | if (!context->input || !context->output || !context->state) { |
| 1166 | destroyAudioNoiseSuppressorContext(context); |
| 1167 | return NULL; |
| 1168 | } |
| 1169 | return context; |
| 1170 | } |
| 1171 |
| 1172 | static int processAudioNoiseSuppressor( |
| 1173 | AudioNoiseSuppressorContext *context, |
| 1174 | int16_t *samples, |
| 1175 | int sampleCount |
| 1176 | ) { |
| 1177 | if (!context || !samples || sampleCount < 0) { |
| 1178 | return 0; |
| 1179 | } |
| 1180 | int sampleOffset = 0; |
| 1181 | while (sampleOffset < sampleCount) { |
| 1182 | int blockSamples = MIN(context->frame_size, sampleCount - sampleOffset); |
| 1183 | for (int index = 0; index < blockSamples; index++) { |
| 1184 | context->input[index] = samples[sampleOffset + index]; |
| 1185 | } |
| 1186 | for (int index = blockSamples; index < context->frame_size; index++) { |
| 1187 | context->input[index] = 0.0f; |
| 1188 | } |
| 1189 | rnnoise_process_frame(context->state, context->output, context->input); |
| 1190 | for (int index = 0; index < blockSamples; index++) { |
| 1191 | if (!isfinite(context->output[index])) { |
| 1192 | return 0; |
| 1193 | } |
| 1194 | } |
| 1195 | for (int index = 0; index < blockSamples; index++) { |
| 1196 | float sample = fmaxf(-32768.0f, fminf(32767.0f, context->output[index])); |
| 1197 | samples[sampleOffset + index] = (int16_t) lrintf(sample); |
| 1198 | } |
| 1199 | sampleOffset += blockSamples; |
| 1200 | } |
| 1201 | return 1; |
| 1202 | } |
| 1203 |
| 1204 | typedef struct { |
| 1205 | opus_int32 rate; |
| 1206 | opus_int32 coding_rate; |
| 1207 | ogg_int32_t packet_id; |
| 1208 | OpusEncoder *encoder; |
| 1209 | uint8_t *packet; |
| 1210 | ogg_stream_state stream; |
| 1211 | int stream_initialized; |
| 1212 | FILE *file; |
| 1213 | oe_enc_opt options; |
| 1214 | OpusHeader header; |
| 1215 | opus_int32 min_bytes; |
| 1216 | int max_frame_bytes; |
| 1217 | ogg_packet ogg_packet; |
| 1218 | ogg_page page; |
| 1219 | opus_int64 bytes_written; |
| 1220 | opus_int64 pages_out; |
| 1221 | opus_int64 total_samples; |
| 1222 | ogg_int64_t encoded_granule_position; |
| 1223 | ogg_int64_t last_granule_position; |
| 1224 | int last_segments; |
| 1225 | int16_t pending_frame[960]; |
| 1226 | int pending_samples; |
| 1227 | } AudioRecorderContext; |
| 1228 |
| 1229 | static volatile int32_t recorder_serial = 1; |
| 1230 |
| 1231 | static void destroyAudioRecorderContext(AudioRecorderContext *recorder) { |
| 1232 | if (!recorder) { |
| 1233 | return; |
| 1234 | } |
| 1235 |
| 1236 | if (recorder->stream_initialized) { |
| 1237 | while (ogg_stream_flush(&recorder->stream, &recorder->page)) { |
| 1238 | if (recorder->file) { |
| 1239 | writeOggPage(&recorder->page, recorder->file); |
| 1240 | } |
| 1241 | } |
| 1242 | ogg_stream_clear(&recorder->stream); |
| 1243 | } |
| 1244 | if (recorder->encoder) { |
| 1245 | opus_encoder_destroy(recorder->encoder); |
| 1246 | } |
| 1247 | if (recorder->packet) { |
| 1248 | free(recorder->packet); |
| 1249 | } |
| 1250 | if (recorder->options.comments) { |
| 1251 | free(recorder->options.comments); |
| 1252 | } |
| 1253 | if (recorder->file) { |
| 1254 | fclose(recorder->file); |
| 1255 | } |
| 1256 | free(recorder); |
| 1257 | } |
| 1258 |
| 1259 | static AudioRecorderContext *createAudioRecorderContext(const char *path, opus_int32 sampleRate) { |
| 1260 | if (!path) { |
| 1261 | LOGE("path is null"); |
| 1262 | return NULL; |
| 1263 | } |
| 1264 |
| 1265 | AudioRecorderContext *recorder = calloc(1, sizeof(AudioRecorderContext)); |
| 1266 | if (!recorder) { |
| 1267 | LOGE("Unable to allocate audio recorder context"); |
| 1268 | return NULL; |
| 1269 | } |
| 1270 |
| 1271 | recorder->packet_id = -1; |
| 1272 | recorder->coding_rate = sampleRate; |
| 1273 | recorder->rate = sampleRate; |
| 1274 |
| 1275 | recorder->file = fopen(path, "w"); |
| 1276 | if (!recorder->file) { |
| 1277 | LOGE("error cannot open file: %s", path); |
| 1278 | destroyAudioRecorderContext(recorder); |
| 1279 | return NULL; |
| 1280 | } |
| 1281 |
| 1282 | recorder->options.rate = recorder->rate; |
| 1283 | recorder->options.gain = 0; |
| 1284 | recorder->options.endianness = 0; |
| 1285 | recorder->options.copy_comments = 0; |
| 1286 | recorder->options.rawmode = 0; |
| 1287 | recorder->options.ignorelength = 0; |
| 1288 | recorder->options.samplesize = 16; |
| 1289 | recorder->options.channels = 1; |
| 1290 | recorder->options.skip = 0; |
| 1291 |
| 1292 | comment_init( |
| 1293 | &recorder->options.comments, |
| 1294 | &recorder->options.comments_length, |
| 1295 | opus_get_version_string() |
| 1296 | ); |
| 1297 | if (!recorder->options.comments) { |
| 1298 | LOGE("Unable to allocate Opus comments"); |
| 1299 | destroyAudioRecorderContext(recorder); |
| 1300 | return NULL; |
| 1301 | } |
| 1302 |
| 1303 | if (recorder->rate != recorder->coding_rate) { |
| 1304 | LOGE("Invalid rate"); |
| 1305 | destroyAudioRecorderContext(recorder); |
| 1306 | return NULL; |
| 1307 | } |
| 1308 |
| 1309 | recorder->header.channels = 1; |
| 1310 | recorder->header.channel_mapping = 0; |
| 1311 | recorder->header.input_sample_rate = recorder->rate; |
| 1312 | recorder->header.gain = recorder->options.gain; |
| 1313 | recorder->header.nb_streams = 1; |
| 1314 |
| 1315 | int result = OPUS_OK; |
| 1316 | recorder->encoder = opus_encoder_create( |
| 1317 | recorder->coding_rate, |
| 1318 | 1, |
| 1319 | opus_application, |
| 1320 | &result |
| 1321 | ); |
| 1322 | if (result != OPUS_OK) { |
| 1323 | LOGE("Error cannot create encoder: %s", opus_strerror(result)); |
| 1324 | destroyAudioRecorderContext(recorder); |
| 1325 | return NULL; |
| 1326 | } |
| 1327 |
| 1328 | recorder->min_bytes = recorder->max_frame_bytes = |
| 1329 | (1275 * 3 + 7) * recorder->header.nb_streams; |
| 1330 | recorder->packet = malloc(recorder->max_frame_bytes); |
| 1331 | if (!recorder->packet) { |
| 1332 | LOGE("Unable to allocate Opus packet buffer"); |
| 1333 | destroyAudioRecorderContext(recorder); |
| 1334 | return NULL; |
| 1335 | } |
| 1336 |
| 1337 | result = opus_encoder_ctl(recorder->encoder, OPUS_SET_BITRATE(bitrate)); |
| 1338 | //result = opus_encoder_ctl(_encoder, OPUS_SET_COMPLEXITY(10)); |
| 1339 | if (result != OPUS_OK) { |
| 1340 | LOGE("Error OPUS_SET_BITRATE returned: %s", opus_strerror(result)); |
| 1341 | destroyAudioRecorderContext(recorder); |
| 1342 | return NULL; |
| 1343 | } |
| 1344 |
| 1345 | #ifdef OPUS_SET_LSB_DEPTH |
| 1346 | result = opus_encoder_ctl( |
| 1347 | recorder->encoder, |
| 1348 | OPUS_SET_LSB_DEPTH(MAX(8, MIN(24, recorder->options.samplesize))) |
| 1349 | ); |
| 1350 | if (result != OPUS_OK) { |
| 1351 | LOGE("Warning OPUS_SET_LSB_DEPTH returned: %s", opus_strerror(result)); |
| 1352 | } |
| 1353 | #endif |
| 1354 |
| 1355 | opus_int32 lookahead; |
| 1356 | result = opus_encoder_ctl(recorder->encoder, OPUS_GET_LOOKAHEAD(&lookahead)); |
| 1357 | if (result != OPUS_OK) { |
| 1358 | LOGE("Error OPUS_GET_LOOKAHEAD returned: %s", opus_strerror(result)); |
| 1359 | destroyAudioRecorderContext(recorder); |
| 1360 | return NULL; |
| 1361 | } |
| 1362 |
| 1363 | recorder->options.skip += lookahead; |
| 1364 | recorder->header.preskip = (int) ( |
| 1365 | recorder->options.skip * (48000.0 / recorder->coding_rate) |
| 1366 | ); |
| 1367 | recorder->options.extraout = (int) ( |
| 1368 | recorder->header.preskip * (recorder->rate / 48000.0) |
| 1369 | ); |
| 1370 |
| 1371 | int serial = __sync_fetch_and_add(&recorder_serial, 1) |
| 1372 | ^ (int) time(NULL) |
| 1373 | ^ (int) (uintptr_t) recorder; |
| 1374 | if (ogg_stream_init(&recorder->stream, serial) == -1) { |
| 1375 | LOGE("Error: stream init failed"); |
| 1376 | destroyAudioRecorderContext(recorder); |
| 1377 | return NULL; |
| 1378 | } |
| 1379 | recorder->stream_initialized = 1; |
| 1380 |
| 1381 | unsigned char header_data[100]; |
| 1382 | int packet_size = opus_header_to_packet(&recorder->header, header_data, 100); |
| 1383 | recorder->ogg_packet.packet = header_data; |
| 1384 | recorder->ogg_packet.bytes = packet_size; |
| 1385 | recorder->ogg_packet.b_o_s = 1; |
| 1386 | recorder->ogg_packet.e_o_s = 0; |
| 1387 | recorder->ogg_packet.granulepos = 0; |
| 1388 | recorder->ogg_packet.packetno = 0; |
| 1389 | ogg_stream_packetin(&recorder->stream, &recorder->ogg_packet); |
| 1390 |
| 1391 | while ((result = ogg_stream_flush(&recorder->stream, &recorder->page))) { |
| 1392 | if (!result) { |
| 1393 | break; |
| 1394 | } |
| 1395 |
| 1396 | int pageBytesWritten = writeOggPage(&recorder->page, recorder->file); |
| 1397 | if (pageBytesWritten != recorder->page.header_len + recorder->page.body_len) { |
| 1398 | LOGE("Error: failed writing header to output stream"); |
| 1399 | destroyAudioRecorderContext(recorder); |
| 1400 | return NULL; |
| 1401 | } |
| 1402 | recorder->bytes_written += pageBytesWritten; |
| 1403 | recorder->pages_out++; |
| 1404 | } |
| 1405 |
| 1406 | comment_pad( |
| 1407 | &recorder->options.comments, |
| 1408 | &recorder->options.comments_length, |
| 1409 | comment_padding |
| 1410 | ); |
| 1411 | recorder->ogg_packet.packet = (unsigned char *) recorder->options.comments; |
| 1412 | recorder->ogg_packet.bytes = recorder->options.comments_length; |
| 1413 | recorder->ogg_packet.b_o_s = 0; |
| 1414 | recorder->ogg_packet.e_o_s = 0; |
| 1415 | recorder->ogg_packet.granulepos = 0; |
| 1416 | recorder->ogg_packet.packetno = 1; |
| 1417 | ogg_stream_packetin(&recorder->stream, &recorder->ogg_packet); |
| 1418 |
| 1419 | while ((result = ogg_stream_flush(&recorder->stream, &recorder->page))) { |
| 1420 | if (result == 0) { |
| 1421 | break; |
| 1422 | } |
| 1423 |
| 1424 | int writtenPageBytes = writeOggPage(&recorder->page, recorder->file); |
| 1425 | if (writtenPageBytes != recorder->page.header_len + recorder->page.body_len) { |
| 1426 | LOGE("Error: failed writing header to output stream"); |
| 1427 | destroyAudioRecorderContext(recorder); |
| 1428 | return NULL; |
| 1429 | } |
| 1430 |
| 1431 | recorder->bytes_written += writtenPageBytes; |
| 1432 | recorder->pages_out++; |
| 1433 | } |
| 1434 |
| 1435 | free(recorder->options.comments); |
| 1436 | recorder->options.comments = NULL; |
| 1437 |
| 1438 | return recorder; |
| 1439 | } |
| 1440 |
| 1441 | // countedSamples is how many of the encoded samples belong to the stream duration; padding |
| 1442 | // frames that only flush the encoder lookahead count zero. |
| 1443 | static int writeAudioRecorderContextPacket( |
| 1444 | AudioRecorderContext *recorder, |
| 1445 | uint8_t *framePcmBytes, |
| 1446 | uint32_t frameByteCount, |
| 1447 | opus_int32 countedSamples, |
| 1448 | int end |
| 1449 | ) { |
| 1450 | if (!recorder || !recorder->encoder || !recorder->file) { |
| 1451 | return 0; |
| 1452 | } |
| 1453 | size_t cur_frame_size = frame_size; |
| 1454 | recorder->packet_id++; |
| 1455 |
| 1456 | opus_int32 nb_samples = frameByteCount / 2; |
| 1457 | recorder->total_samples += countedSamples; |
| 1458 | recorder->ogg_packet.e_o_s = end; |
| 1459 |
| 1460 | int nbBytes = 0; |
| 1461 | int size_segments = 0; |
| 1462 |
| 1463 | if (nb_samples != 0) { |
| 1464 | uint8_t *paddedFrameBytes = framePcmBytes; |
| 1465 | int freePaddedFrameBytes = 0; |
| 1466 |
| 1467 | if (nb_samples < cur_frame_size) { |
| 1468 | paddedFrameBytes = malloc(cur_frame_size * 2); |
| 1469 | freePaddedFrameBytes = 1; |
| 1470 | memcpy(paddedFrameBytes, framePcmBytes, frameByteCount); |
| 1471 | memset(paddedFrameBytes + nb_samples * 2, 0, cur_frame_size * 2 - nb_samples * 2); |
| 1472 | } |
| 1473 |
| 1474 | nbBytes = opus_encode( |
| 1475 | recorder->encoder, |
| 1476 | (opus_int16 *) paddedFrameBytes, |
| 1477 | cur_frame_size, |
| 1478 | recorder->packet, |
| 1479 | recorder->max_frame_bytes / 10 |
| 1480 | ); |
| 1481 | if (freePaddedFrameBytes) { |
| 1482 | free(paddedFrameBytes); |
| 1483 | } |
| 1484 |
| 1485 | if (nbBytes < 0) { |
| 1486 | LOGE("Encoding failed: %s. Aborting.", opus_strerror(nbBytes)); |
| 1487 | return 0; |
| 1488 | } |
| 1489 |
| 1490 | recorder->encoded_granule_position += |
| 1491 | cur_frame_size * 48000 / recorder->coding_rate; |
| 1492 | size_segments = (nbBytes + 255) / 255; |
| 1493 | recorder->min_bytes = MIN(nbBytes, recorder->min_bytes); |
| 1494 | } |
| 1495 |
| 1496 | while ((((size_segments <= 255) |
| 1497 | && (recorder->last_segments + size_segments > 255)) |
| 1498 | || (recorder->encoded_granule_position |
| 1499 | - recorder->last_granule_position > max_ogg_delay)) |
| 1500 | && ogg_stream_flush_fill( |
| 1501 | &recorder->stream, |
| 1502 | &recorder->page, |
| 1503 | 255 * 255 |
| 1504 | )) { |
| 1505 | if (ogg_page_packets(&recorder->page) != 0) { |
| 1506 | recorder->last_granule_position = ogg_page_granulepos(&recorder->page); |
| 1507 | } |
| 1508 |
| 1509 | recorder->last_segments -= recorder->page.header[26]; |
| 1510 | int writtenPageBytes = writeOggPage(&recorder->page, recorder->file); |
| 1511 | if (writtenPageBytes != recorder->page.header_len + recorder->page.body_len) { |
| 1512 | LOGE("Error: failed writing data to output stream"); |
| 1513 | return 0; |
| 1514 | } |
| 1515 | recorder->bytes_written += writtenPageBytes; |
| 1516 | recorder->pages_out++; |
| 1517 | } |
| 1518 |
| 1519 | recorder->ogg_packet.packet = recorder->packet; |
| 1520 | recorder->ogg_packet.bytes = nbBytes; |
| 1521 | recorder->ogg_packet.b_o_s = 0; |
| 1522 | recorder->ogg_packet.granulepos = recorder->encoded_granule_position; |
| 1523 | if (recorder->ogg_packet.e_o_s) { |
| 1524 | recorder->ogg_packet.granulepos = ( |
| 1525 | (recorder->total_samples * 48000 + recorder->rate - 1) |
| 1526 | / recorder->rate |
| 1527 | ) + recorder->header.preskip; |
| 1528 | } |
| 1529 | recorder->ogg_packet.packetno = 2 + recorder->packet_id; |
| 1530 | ogg_stream_packetin(&recorder->stream, &recorder->ogg_packet); |
| 1531 | recorder->last_segments += size_segments; |
| 1532 |
| 1533 | while ((recorder->ogg_packet.e_o_s |
| 1534 | || (recorder->encoded_granule_position |
| 1535 | + (frame_size * 48000 / recorder->coding_rate) |
| 1536 | - recorder->last_granule_position > max_ogg_delay) |
| 1537 | || (recorder->last_segments >= 255)) |
| 1538 | ? ogg_stream_flush_fill(&recorder->stream, &recorder->page, 255 * 255) |
| 1539 | : ogg_stream_pageout_fill(&recorder->stream, &recorder->page, 255 * 255)) { |
| 1540 | if (ogg_page_packets(&recorder->page) != 0) { |
| 1541 | recorder->last_granule_position = ogg_page_granulepos(&recorder->page); |
| 1542 | } |
| 1543 | recorder->last_segments -= recorder->page.header[26]; |
| 1544 | int writtenPageBytes = writeOggPage(&recorder->page, recorder->file); |
| 1545 | if (writtenPageBytes != recorder->page.header_len + recorder->page.body_len) { |
| 1546 | LOGE("Error: failed writing data to output stream"); |
| 1547 | return 0; |
| 1548 | } |
| 1549 | recorder->bytes_written += writtenPageBytes; |
| 1550 | recorder->pages_out++; |
| 1551 | } |
| 1552 |
| 1553 | return 1; |
| 1554 | } |
| 1555 |
| 1556 | static int writeAudioRecorderContextFrame( |
| 1557 | AudioRecorderContext *recorder, |
| 1558 | uint8_t *framePcmBytes, |
| 1559 | uint32_t frameByteCount, |
| 1560 | int end |
| 1561 | ) { |
| 1562 | return writeAudioRecorderContextPacket( |
| 1563 | recorder, |
| 1564 | framePcmBytes, |
| 1565 | frameByteCount, |
| 1566 | (opus_int32) (frameByteCount / 2), |
| 1567 | end |
| 1568 | ); |
| 1569 | } |
| 1570 |
| 1571 | // Writes the buffered tail and enough silent frames to push the encoder lookahead out, then |
| 1572 | // marks the last packet as end of stream. Its granule position trims the padding, so the |
| 1573 | // stream ends exactly after the last captured sample. |
| 1574 | static int finishAudioRecorderStream(AudioRecorderContext *recorder) { |
| 1575 | if (!recorder) { |
| 1576 | return 0; |
| 1577 | } |
| 1578 | if (recorder->pending_samples > 0) { |
| 1579 | int pendingSamples = recorder->pending_samples; |
| 1580 | recorder->pending_samples = 0; |
| 1581 | if (!writeAudioRecorderContextFrame( |
| 1582 | recorder, |
| 1583 | (uint8_t *) recorder->pending_frame, |
| 1584 | pendingSamples * sizeof(int16_t), |
| 1585 | 0 |
| 1586 | )) { |
| 1587 | return 0; |
| 1588 | } |
| 1589 | } |
| 1590 | ogg_int64_t endGranulePosition = |
| 1591 | (recorder->total_samples * 48000 + recorder->rate - 1) / recorder->rate |
| 1592 | + recorder->header.preskip; |
| 1593 | int16_t silence[960]; |
| 1594 | memset(silence, 0, sizeof(silence)); |
| 1595 | while (1) { |
| 1596 | int end = recorder->encoded_granule_position |
| 1597 | + frame_size * 48000 / recorder->coding_rate >= endGranulePosition; |
| 1598 | if (!writeAudioRecorderContextPacket( |
| 1599 | recorder, |
| 1600 | (uint8_t *) silence, |
| 1601 | sizeof(silence), |
| 1602 | 0, |
| 1603 | end |
| 1604 | )) { |
| 1605 | return 0; |
| 1606 | } |
| 1607 | if (end) { |
| 1608 | return 1; |
| 1609 | } |
| 1610 | } |
| 1611 | } |
| 1612 |
| 1613 | static jlong flushAudioRecorderContext(AudioRecorderContext *recorder) { |
| 1614 | if (!recorder || !recorder->file || fflush(recorder->file) != 0) { |
| 1615 | return -1; |
| 1616 | } |
| 1617 | long position = ftell(recorder->file); |
| 1618 | return position < 0 ? -1 : (jlong) position; |
| 1619 | } |
| 1620 |
| 1621 | static int cropAudioRecorderOpusAudio(const char *inputPath, const char *outputPath, float startTimeMs, float endTimeMs) { |
| 1622 | int error; |
| 1623 | OggOpusFile *opusFile = op_open_file(inputPath, &error); |
| 1624 | if (!opusFile || error != OPUS_OK) { |
| 1625 | LOGE("Failed to open input opus file: %s", opus_strerror(error)); |
| 1626 | return 0; |
| 1627 | } |
| 1628 |
| 1629 | const OpusHead *head = op_head(opusFile, -1); |
| 1630 | if (!head) { |
| 1631 | LOGE("Failed to read Opus header"); |
| 1632 | op_free(opusFile); |
| 1633 | return 0; |
| 1634 | } |
| 1635 |
| 1636 | int channels = head->channel_count; |
| 1637 | opus_int64 total_source_samples = op_pcm_total(opusFile, -1); |
| 1638 | if (total_source_samples < 0) { |
| 1639 | LOGE("Failed to get source sample count: %lld", (long long) total_source_samples); |
| 1640 | op_free(opusFile); |
| 1641 | return 0; |
| 1642 | } |
| 1643 |
| 1644 | opus_int32 rate = 48000; |
| 1645 |
| 1646 | opus_int64 start_sample = MAX(0, MIN(total_source_samples, (opus_int64) ((startTimeMs / 1000.0) * rate))); |
| 1647 | opus_int64 end_sample = MAX(0, MIN(total_source_samples, (opus_int64) ((endTimeMs / 1000.0) * rate))); |
| 1648 | opus_int64 crop_length = end_sample - start_sample; |
| 1649 |
| 1650 | if (start_sample >= total_source_samples || end_sample > total_source_samples || start_sample >= end_sample) { |
| 1651 | LOGE("Invalid crop range"); |
| 1652 | op_free(opusFile); |
| 1653 | return 0; |
| 1654 | } |
| 1655 |
| 1656 | if (op_pcm_seek(opusFile, start_sample) != 0) { |
| 1657 | LOGE("Failed to seek to start sample"); |
| 1658 | op_free(opusFile); |
| 1659 | return 0; |
| 1660 | } |
| 1661 |
| 1662 | AudioRecorderContext *recorder = createAudioRecorderContext(outputPath, rate); |
| 1663 | if (!recorder) { |
| 1664 | LOGE("Failed to init recorder"); |
| 1665 | op_free(opusFile); |
| 1666 | return 0; |
| 1667 | } |
| 1668 |
| 1669 | int16_t *buffer = malloc(sizeof(int16_t) * frame_size * channels); |
| 1670 | if (!buffer) { |
| 1671 | LOGE("Out of memory"); |
| 1672 | destroyAudioRecorderContext(recorder); |
| 1673 | op_free(opusFile); |
| 1674 | return 0; |
| 1675 | } |
| 1676 |
| 1677 | int success = 1; |
| 1678 | opus_int64 remaining_samples = crop_length; |
| 1679 | while (remaining_samples > 0) { |
| 1680 | int max_samples = (int) MIN(960, remaining_samples / channels); |
| 1681 | if (max_samples <= 0) { |
| 1682 | break; |
| 1683 | } |
| 1684 | int samples_read = op_read(opusFile, buffer, max_samples * channels, NULL); |
| 1685 | if (samples_read < 0) { |
| 1686 | LOGE("Decoding error from op_read(): %d", samples_read); |
| 1687 | success = 0; |
| 1688 | break; |
| 1689 | } |
| 1690 | if (samples_read == 0) { |
| 1691 | break; |
| 1692 | } |
| 1693 | remaining_samples -= samples_read; |
| 1694 |
| 1695 | size_t byte_count = samples_read * sizeof(int16_t); |
| 1696 | if (!writeAudioRecorderContextFrame(recorder, (uint8_t *)buffer, byte_count, 0)) { |
| 1697 | LOGE("Failed to write frame"); |
| 1698 | success = 0; |
| 1699 | break; |
| 1700 | } |
| 1701 | } |
| 1702 | if (success && !finishAudioRecorderStream(recorder)) { |
| 1703 | LOGE("Failed to finish cropped stream"); |
| 1704 | success = 0; |
| 1705 | } |
| 1706 |
| 1707 | free(buffer); |
| 1708 | destroyAudioRecorderContext(recorder); |
| 1709 | op_free(opusFile); |
| 1710 |
| 1711 | return success; |
| 1712 | } |
| 1713 |
| 1714 | // Re-encodes [startMs, endMs) of the prefix file into the recorder; a negative endMs keeps the |
| 1715 | // rest of the file. |
| 1716 | static int appendRecorderPrefix( |
| 1717 | AudioRecorderContext *recorder, |
| 1718 | const char *prefixPath, |
| 1719 | opus_int64 startMs, |
| 1720 | opus_int64 endMs |
| 1721 | ) { |
| 1722 | if (!recorder || !prefixPath) { |
| 1723 | return 0; |
| 1724 | } |
| 1725 |
| 1726 | int error = OPUS_OK; |
| 1727 | OggOpusFile *prefixFile = op_open_file(prefixPath, &error); |
| 1728 | if (!prefixFile || error != OPUS_OK) { |
| 1729 | LOGE("Failed to open Opus prefix: %s", opus_strerror(error)); |
| 1730 | if (prefixFile) { |
| 1731 | op_free(prefixFile); |
| 1732 | } |
| 1733 | return 0; |
| 1734 | } |
| 1735 |
| 1736 | const OpusHead *head = op_head(prefixFile, -1); |
| 1737 | if (!head || head->channel_count != 1) { |
| 1738 | LOGE("Unsupported Opus prefix channel count"); |
| 1739 | op_free(prefixFile); |
| 1740 | return 0; |
| 1741 | } |
| 1742 |
| 1743 | opus_int64 remainingSamples = INT64_MAX; |
| 1744 | if (startMs > 0 || endMs >= 0) { |
| 1745 | opus_int64 totalSamples = op_pcm_total(prefixFile, -1); |
| 1746 | if (totalSamples < 0) { |
| 1747 | LOGE("Failed to get Opus prefix length: %lld", (long long) totalSamples); |
| 1748 | op_free(prefixFile); |
| 1749 | return 0; |
| 1750 | } |
| 1751 | opus_int64 startSample = MAX(0, MIN(totalSamples, startMs * 48000 / 1000)); |
| 1752 | opus_int64 endSample = endMs < 0 |
| 1753 | ? totalSamples |
| 1754 | : MAX(startSample, MIN(totalSamples, endMs * 48000 / 1000)); |
| 1755 | if (startSample > 0 && op_pcm_seek(prefixFile, startSample) != 0) { |
| 1756 | LOGE("Failed to seek Opus prefix to %lld", (long long) startSample); |
| 1757 | op_free(prefixFile); |
| 1758 | return 0; |
| 1759 | } |
| 1760 | remainingSamples = endSample - startSample; |
| 1761 | } |
| 1762 |
| 1763 | int16_t *buffer = malloc(sizeof(int16_t) * frame_size); |
| 1764 | if (!buffer) { |
| 1765 | LOGE("Out of memory while rebuilding Opus prefix"); |
| 1766 | op_free(prefixFile); |
| 1767 | return 0; |
| 1768 | } |
| 1769 |
| 1770 | int success = 1; |
| 1771 | int bufferedSamples = 0; |
| 1772 | while (remainingSamples > 0) { |
| 1773 | int samplesRead = op_read( |
| 1774 | prefixFile, |
| 1775 | buffer + bufferedSamples, |
| 1776 | (int) MIN(frame_size - bufferedSamples, remainingSamples), |
| 1777 | NULL |
| 1778 | ); |
| 1779 | if (samplesRead < 0) { |
| 1780 | LOGE("Failed to decode Opus prefix: %d", samplesRead); |
| 1781 | success = 0; |
| 1782 | break; |
| 1783 | } |
| 1784 | if (samplesRead == 0) { |
| 1785 | break; |
| 1786 | } |
| 1787 | remainingSamples -= samplesRead; |
| 1788 | bufferedSamples += samplesRead; |
| 1789 | if (bufferedSamples == frame_size) { |
| 1790 | if (!writeAudioRecorderContextFrame( |
| 1791 | recorder, |
| 1792 | (uint8_t *) buffer, |
| 1793 | frame_size * sizeof(int16_t), |
| 1794 | 0 |
| 1795 | )) { |
| 1796 | success = 0; |
| 1797 | break; |
| 1798 | } |
| 1799 | bufferedSamples = 0; |
| 1800 | } |
| 1801 | } |
| 1802 |
| 1803 | if (success && bufferedSamples > 0) { |
| 1804 | memcpy( |
| 1805 | recorder->pending_frame, |
| 1806 | buffer, |
| 1807 | bufferedSamples * sizeof(int16_t) |
| 1808 | ); |
| 1809 | recorder->pending_samples = bufferedSamples; |
| 1810 | } |
| 1811 | free(buffer); |
| 1812 | op_free(prefixFile); |
| 1813 | return success; |
| 1814 | } |
| 1815 |
| 1816 | static int writeAudioRecorderFrame( |
| 1817 | AudioRecorderContext *recorder, |
| 1818 | uint8_t *pcmBytes, |
| 1819 | uint32_t byteCount |
| 1820 | ) { |
| 1821 | if (!recorder || (byteCount > 0 && !pcmBytes)) { |
| 1822 | return 0; |
| 1823 | } |
| 1824 |
| 1825 | int16_t *samples = (int16_t *) pcmBytes; |
| 1826 | int sampleCount = (int) byteCount / 2; |
| 1827 | int sampleOffset = 0; |
| 1828 |
| 1829 | while (sampleOffset < sampleCount) { |
| 1830 | if (recorder->pending_samples == 0 |
| 1831 | && sampleCount - sampleOffset >= frame_size) { |
| 1832 | if (!writeAudioRecorderContextFrame( |
| 1833 | recorder, |
| 1834 | (uint8_t *) (samples + sampleOffset), |
| 1835 | frame_size * sizeof(int16_t), |
| 1836 | 0 |
| 1837 | )) { |
| 1838 | return 0; |
| 1839 | } |
| 1840 | sampleOffset += frame_size; |
| 1841 | continue; |
| 1842 | } |
| 1843 |
| 1844 | int copySamples = MIN( |
| 1845 | frame_size - recorder->pending_samples, |
| 1846 | sampleCount - sampleOffset |
| 1847 | ); |
| 1848 | memcpy( |
| 1849 | recorder->pending_frame + recorder->pending_samples, |
| 1850 | samples + sampleOffset, |
| 1851 | copySamples * sizeof(int16_t) |
| 1852 | ); |
| 1853 | recorder->pending_samples += copySamples; |
| 1854 | sampleOffset += copySamples; |
| 1855 |
| 1856 | if (recorder->pending_samples == frame_size) { |
| 1857 | if (!writeAudioRecorderContextFrame( |
| 1858 | recorder, |
| 1859 | (uint8_t *) recorder->pending_frame, |
| 1860 | frame_size * sizeof(int16_t), |
| 1861 | 0 |
| 1862 | )) { |
| 1863 | return 0; |
| 1864 | } |
| 1865 | recorder->pending_samples = 0; |
| 1866 | } |
| 1867 | } |
| 1868 | return 1; |
| 1869 | } |
| 1870 |
| 1871 | JNIEXPORT jlong Java_org_telegram_utils_recorder_audio_AudioRecorderNative_nCreate( |
| 1872 | JNIEnv *env, |
| 1873 | jclass clazz, |
| 1874 | jstring path, |
| 1875 | jint sampleRate, |
| 1876 | jstring prefixPath, |
| 1877 | jlong prefixStartMs, |
| 1878 | jlong prefixEndMs |
| 1879 | ) { |
| 1880 | const char *pathString = (*env)->GetStringUTFChars(env, path, 0); |
| 1881 | if (!pathString) { |
| 1882 | return 0; |
| 1883 | } |
| 1884 |
| 1885 | AudioRecorderContext *recorder = createAudioRecorderContext(pathString, sampleRate); |
| 1886 | (*env)->ReleaseStringUTFChars(env, path, pathString); |
| 1887 | if (!recorder) { |
| 1888 | return 0; |
| 1889 | } |
| 1890 |
| 1891 | if (prefixPath) { |
| 1892 | const char *prefixPathString = (*env)->GetStringUTFChars(env, prefixPath, 0); |
| 1893 | if (!prefixPathString) { |
| 1894 | destroyAudioRecorderContext(recorder); |
| 1895 | return 0; |
| 1896 | } |
| 1897 | int prefixResult = appendRecorderPrefix( |
| 1898 | recorder, |
| 1899 | prefixPathString, |
| 1900 | prefixStartMs, |
| 1901 | prefixEndMs |
| 1902 | ); |
| 1903 | (*env)->ReleaseStringUTFChars(env, prefixPath, prefixPathString); |
| 1904 | if (!prefixResult) { |
| 1905 | destroyAudioRecorderContext(recorder); |
| 1906 | return 0; |
| 1907 | } |
| 1908 | } |
| 1909 |
| 1910 | return (jlong) (intptr_t) recorder; |
| 1911 | } |
| 1912 |
| 1913 | JNIEXPORT jint Java_org_telegram_utils_recorder_audio_AudioRecorderNative_nWriteFrame( |
| 1914 | JNIEnv *env, |
| 1915 | jclass clazz, |
| 1916 | jlong handle, |
| 1917 | jobject frame, |
| 1918 | jint length |
| 1919 | ) { |
| 1920 | AudioRecorderContext *recorder = (AudioRecorderContext *) (intptr_t) handle; |
| 1921 | jbyte *frameBytes = (*env)->GetDirectBufferAddress(env, frame); |
| 1922 | jlong capacity = (*env)->GetDirectBufferCapacity(env, frame); |
| 1923 | if (!recorder || !frameBytes || length < 0 || capacity < length) { |
| 1924 | return 0; |
| 1925 | } |
| 1926 | // A short frame is just the tail of the capture; the stream ends only in nFinish. |
| 1927 | return writeAudioRecorderFrame(recorder, (uint8_t *) frameBytes, (uint32_t) length); |
| 1928 | } |
| 1929 |
| 1930 | JNIEXPORT jlong Java_org_telegram_utils_recorder_audio_AudioRecorderNative_nFlush( |
| 1931 | JNIEnv *env, |
| 1932 | jclass clazz, |
| 1933 | jlong handle |
| 1934 | ) { |
| 1935 | AudioRecorderContext *recorder = (AudioRecorderContext *) (intptr_t) handle; |
| 1936 | return flushAudioRecorderContext(recorder); |
| 1937 | } |
| 1938 |
| 1939 | JNIEXPORT jboolean Java_org_telegram_utils_recorder_audio_AudioRecorderNative_nFinish( |
| 1940 | JNIEnv *env, |
| 1941 | jclass clazz, |
| 1942 | jlong handle |
| 1943 | ) { |
| 1944 | AudioRecorderContext *recorder = (AudioRecorderContext *) (intptr_t) handle; |
| 1945 | if (!recorder) { |
| 1946 | return JNI_FALSE; |
| 1947 | } |
| 1948 |
| 1949 | int result = finishAudioRecorderStream(recorder); |
| 1950 | if (result && flushAudioRecorderContext(recorder) < 0) { |
| 1951 | result = 0; |
| 1952 | } |
| 1953 | destroyAudioRecorderContext(recorder); |
| 1954 | return result ? JNI_TRUE : JNI_FALSE; |
| 1955 | } |
| 1956 |
| 1957 | JNIEXPORT void Java_org_telegram_utils_recorder_audio_AudioRecorderNative_nDestroy( |
| 1958 | JNIEnv *env, |
| 1959 | jclass clazz, |
| 1960 | jlong handle |
| 1961 | ) { |
| 1962 | destroyAudioRecorderContext((AudioRecorderContext *) (intptr_t) handle); |
| 1963 | } |
| 1964 |
| 1965 | JNIEXPORT jboolean Java_org_telegram_utils_recorder_audio_AudioRecorderNative_nCropOpusFile( |
| 1966 | JNIEnv *env, |
| 1967 | jclass clazz, |
| 1968 | jstring source, |
| 1969 | jstring destination, |
| 1970 | jlong startMs, |
| 1971 | jlong endMs |
| 1972 | ) { |
| 1973 | const char *sourceString = (*env)->GetStringUTFChars(env, source, 0); |
| 1974 | const char *destinationString = (*env)->GetStringUTFChars(env, destination, 0); |
| 1975 | int result = cropAudioRecorderOpusAudio(sourceString, destinationString, startMs, endMs); |
| 1976 | (*env)->ReleaseStringUTFChars(env, source, sourceString); |
| 1977 | (*env)->ReleaseStringUTFChars(env, destination, destinationString); |
| 1978 | return result == 1; |
| 1979 | } |
| 1980 |
| 1981 | JNIEXPORT jbyteArray Java_org_telegram_utils_recorder_audio_AudioRecorderNative_nGetWaveform( |
| 1982 | JNIEnv *env, |
| 1983 | jclass clazz, |
| 1984 | jstring path |
| 1985 | ) { |
| 1986 | return Java_org_telegram_messenger_MediaController_getWaveform(env, clazz, path); |
| 1987 | } |
| 1988 |
| 1989 | JNIEXPORT jlong Java_org_telegram_utils_recorder_audio_AudioNoiseSuppressor_nCreate( |
| 1990 | JNIEnv *env, |
| 1991 | jclass clazz |
| 1992 | ) { |
| 1993 | return (jlong) (intptr_t) createAudioNoiseSuppressorContext(); |
| 1994 | } |
| 1995 |
| 1996 | JNIEXPORT jboolean Java_org_telegram_utils_recorder_audio_AudioNoiseSuppressor_nProcess( |
| 1997 | JNIEnv *env, |
| 1998 | jclass clazz, |
| 1999 | jlong handle, |
| 2000 | jobject pcm, |
| 2001 | jint sampleCount |
| 2002 | ) { |
| 2003 | AudioNoiseSuppressorContext *context = |
| 2004 | (AudioNoiseSuppressorContext *) (intptr_t) handle; |
| 2005 | int16_t *samples = (*env)->GetDirectBufferAddress(env, pcm); |
| 2006 | jlong capacity = (*env)->GetDirectBufferCapacity(env, pcm); |
| 2007 | if (!context || !samples || sampleCount < 0 |
| 2008 | || capacity < (jlong) sampleCount * sizeof(int16_t)) { |
| 2009 | return JNI_FALSE; |
| 2010 | } |
| 2011 | return processAudioNoiseSuppressor(context, samples, sampleCount) |
| 2012 | ? JNI_TRUE |
| 2013 | : JNI_FALSE; |
| 2014 | } |
| 2015 |
| 2016 | JNIEXPORT void Java_org_telegram_utils_recorder_audio_AudioNoiseSuppressor_nDestroy( |
| 2017 | JNIEnv *env, |
| 2018 | jclass clazz, |
| 2019 | jlong handle |
| 2020 | ) { |
| 2021 | destroyAudioNoiseSuppressorContext( |
| 2022 | (AudioNoiseSuppressorContext *) (intptr_t) handle |
| 2023 | ); |
| 2024 | } |
| 2025 |