| 5 |
| #include <stdlib.h> |
| 6 | #include <time.h> |
| 7 | #include <opusfile.h> |
| 8 | #include <math.h> |
| 9 | #include "c_utils.h" |
| 10 | #include "libavformat/avformat.h" |
| 11 | #include "libavcodec/avcodec.h" |
| 12 |
| 13 | typedef struct { |
| 14 | int version; |
| 15 | int channels; /* Number of channels: 1..255 */ |
| 16 | int preskip; |
| 17 | ogg_uint32_t input_sample_rate; |
| 18 | int gain; /* in dB S7.8 should be zero whenever possible */ |
| 19 | int channel_mapping; |
| 20 | /* The rest is only used if channel_mapping != 0 */ |
| 21 | int nb_streams; |
| 22 | int nb_coupled; |
| 23 | unsigned char stream_map[255]; |
| 24 | } OpusHeader; |
| 25 |
| 26 | typedef struct { |
| 27 | unsigned char *data; |
| 28 | int maxlen; |
| 29 | int pos; |
| 30 | } Packet; |
| 31 |
| 32 | typedef struct { |
| 33 | const unsigned char *data; |
| 34 | int maxlen; |
| 35 | int pos; |
| 36 | } ROPacket; |
| 37 |
| 38 | typedef struct { |
| 39 | void *readdata; |
| 40 | opus_int64 total_samples_per_channel; |
| 41 | int rawmode; |
| 42 | int channels; |
| 43 | long rate; |
| 44 | int gain; |
| 45 | int samplesize; |
| 46 | int endianness; |
| 47 | char *infilename; |
| 48 | int ignorelength; |
| 49 | int skip; |
| 50 | int extraout; |
| 51 | char *comments; |
| 52 | int comments_length; |
| 53 | int copy_comments; |
| 54 | } oe_enc_opt; |
| 55 |
| 56 | static int write_uint32(Packet *p, ogg_uint32_t val) { |
| 57 | if (p->pos > p->maxlen - 4) { |
| 58 | return 0; |
| 59 | } |
| 60 | p->data[p->pos ] = (val ) & 0xFF; |
| 61 | p->data[p->pos+1] = (val>> 8) & 0xFF; |
| 62 | p->data[p->pos+2] = (val>>16) & 0xFF; |
| 63 | p->data[p->pos+3] = (val>>24) & 0xFF; |
| 64 | p->pos += 4; |
| 65 | return 1; |
| 66 | } |
| 67 |
| 68 | static int write_uint16(Packet *p, ogg_uint16_t val) { |
| 69 | if (p->pos > p->maxlen-2) { |
| 70 | return 0; |
| 71 | } |
| 72 | p->data[p->pos ] = (val ) & 0xFF; |
| 73 | p->data[p->pos+1] = (val>> 8) & 0xFF; |
| 74 | p->pos += 2; |
| 75 | return 1; |
| 76 | } |
| 77 |
| 78 | static int write_chars(Packet *p, const unsigned char *str, int nb_chars) |
| 79 | { |
| 80 | int i; |
| 81 | if (p->pos>p->maxlen-nb_chars) |
| 82 | return 0; |
| 83 | for (i=0;i<nb_chars;i++) |
| 84 | p->data[p->pos++] = str[i]; |
| 85 | return 1; |
| 86 | } |
| 87 |
| 88 | static int read_uint32(ROPacket *p, ogg_uint32_t *val) |
| 89 | { |
| 90 | if (p->pos>p->maxlen-4) |
| 91 | return 0; |
| 92 | *val = (ogg_uint32_t)p->data[p->pos ]; |
| 93 | *val |= (ogg_uint32_t)p->data[p->pos+1]<< 8; |
| 94 | *val |= (ogg_uint32_t)p->data[p->pos+2]<<16; |
| 95 | *val |= (ogg_uint32_t)p->data[p->pos+3]<<24; |
| 96 | p->pos += 4; |
| 97 | return 1; |
| 98 | } |
| 99 |
| 100 | static int read_uint16(ROPacket *p, ogg_uint16_t *val) |
| 101 | { |
| 102 | if (p->pos>p->maxlen-2) |
| 103 | return 0; |
| 104 | *val = (ogg_uint16_t)p->data[p->pos ]; |
| 105 | *val |= (ogg_uint16_t)p->data[p->pos+1]<<8; |
| 106 | p->pos += 2; |
| 107 | return 1; |
| 108 | } |
| 109 |
| 110 | static int read_chars(ROPacket *p, unsigned char *str, int nb_chars) |
| 111 | { |
| 112 | int i; |
| 113 | if (p->pos>p->maxlen-nb_chars) |
| 114 | return 0; |
| 115 | for (i=0;i<nb_chars;i++) |
| 116 | str[i] = p->data[p->pos++]; |
| 117 | return 1; |
| 118 | } |
| 119 |
| 120 | int opus_header_to_packet(const OpusHeader *h, unsigned char *packet, int len) { |
| 121 | int i; |
| 122 | Packet p; |
| 123 | unsigned char ch; |
| 124 |
| 125 | p.data = packet; |
| 126 | p.maxlen = len; |
| 127 | p.pos = 0; |
| 128 | if (len < 19) { |
| 129 | return 0; |
| 130 | } |
| 131 | if (!write_chars(&p, (const unsigned char *)"OpusHead", 8)) { |
| 132 | return 0; |
| 133 | } |
| 134 |
| 135 | ch = 1; |
| 136 | if (!write_chars(&p, &ch, 1)) { |
| 137 | return 0; |
| 138 | } |
| 139 |
| 140 | ch = h->channels; |
| 141 | if (!write_chars(&p, &ch, 1)) { |
| 142 | return 0; |
| 143 | } |
| 144 |
| 145 | if (!write_uint16(&p, h->preskip)) { |
| 146 | return 0; |
| 147 | } |
| 148 |
| 149 | if (!write_uint32(&p, h->input_sample_rate)) { |
| 150 | return 0; |
| 151 | } |
| 152 |
| 153 | if (!write_uint16(&p, h->gain)) { |
| 154 | return 0; |
| 155 | } |
| 156 |
| 157 | ch = h->channel_mapping; |
| 158 | if (!write_chars(&p, &ch, 1)) { |
| 159 | return 0; |
| 160 | } |
| 161 |
| 162 | if (h->channel_mapping != 0) { |
| 163 | ch = h->nb_streams; |
| 164 | if (!write_chars(&p, &ch, 1)) { |
| 165 | return 0; |
| 166 | } |
| 167 |
| 168 | ch = h->nb_coupled; |
| 169 | if (!write_chars(&p, &ch, 1)) { |
| 170 | return 0; |
| 171 | } |
| 172 |
| 173 | /* Multi-stream support */ |
| 174 | for (i = 0; i < h->channels; i++) { |
| 175 | if (!write_chars(&p, &h->stream_map[i], 1)) { |
| 176 | return 0; |
| 177 | } |
| 178 | } |
| 179 | } |
| 180 |
| 181 | return p.pos; |
| 182 | } |
| 183 |
| 184 | #define writeint(buf, base, val) do { buf[base + 3] = ((val) >> 24) & 0xff; \ |
| 185 | buf[base + 2]=((val) >> 16) & 0xff; \ |
| 186 | buf[base + 1]=((val) >> 8) & 0xff; \ |
| 187 | buf[base] = (val) & 0xff; \ |
| 188 | } while(0) |
| 189 |
| 190 | static void comment_init(char **comments, int *length, const char *vendor_string) { |
| 191 | // The 'vendor' field should be the actual encoding library used |
| 192 | size_t vendor_length = strlen(vendor_string); |
| 193 | int user_comment_list_length = 0; |
| 194 | size_t len = 8 + 4 + vendor_length + 4; |
| 195 | char *p = (char *)malloc(len); |
| 196 | memcpy(p, "OpusTags", 8); |
| 197 | writeint(p, 8, vendor_length); |
| 198 | memcpy(p + 12, vendor_string, vendor_length); |
| 199 | writeint(p, 12 + vendor_length, user_comment_list_length); |
| 200 | *length = len; |
| 201 | *comments = p; |
| 202 | } |
| 203 |
| 204 | static void comment_pad(char **comments, int* length, size_t amount) { |
| 205 | if (amount > 0) { |
| 206 | char *p = *comments; |
| 207 | // Make sure there is at least amount worth of padding free, and round up to the maximum that fits in the current ogg segments |
| 208 | size_t newlen = (*length + amount + 255) / 255 * 255 - 1; |
| 209 | p = realloc(p, newlen); |
| 210 | for (int32_t i = *length; i < newlen; i++) { |
| 211 | p[i] = 0; |
| 212 | } |
| 213 | *comments = p; |
| 214 | *length = newlen; |
| 215 | } |
| 216 | } |
| 217 |
| 218 | static int writeOggPage(ogg_page *page, FILE *os) { |
| 219 | int written = fwrite(page->header, sizeof(unsigned char), (size_t) page->header_len, os); |
| 220 | written += fwrite(page->body, sizeof(unsigned char), (size_t) page->body_len, os); |
| 221 | return written; |
| 222 | } |
| 223 |
| 224 | const opus_int32 bitrate = OPUS_BITRATE_MAX; |
| 225 | const opus_int32 frame_size = 960; |
| 226 | const int with_cvbr = 1; |
| 227 | const int max_ogg_delay = 0; |
| 228 | const int comment_padding = 512; |
| 229 |
| 230 | opus_int32 rate = 48000; |
| 231 | opus_int32 coding_rate = 48000; |
| 232 |
| 233 | ogg_int32_t _packetId; |
| 234 | OpusEncoder *_encoder = 0; |
| 235 | uint8_t *_packet = 0; |
| 236 | ogg_stream_state os; |
| 237 | const char *_filePath; |
| 238 | FILE *_fileOs = 0; |
| 239 | oe_enc_opt inopt; |
| 240 | OpusHeader header; |
| 241 | opus_int32 min_bytes; |
| 242 | int max_frame_bytes; |
| 243 | ogg_packet op; |
| 244 | ogg_page og; |
| 245 | opus_int64 bytes_written; |
| 246 | opus_int64 pages_out; |
| 247 | opus_int64 total_samples; |
| 248 | ogg_int64_t enc_granulepos; |
| 249 | ogg_int64_t last_granulepos; |
| 250 | int size_segments; |
| 251 | int last_segments; |
| 252 | int serialno; |
| 253 |
| 254 | void cleanupRecorder() { |
| 255 |
| 256 | if (_fileOs) { |
| 257 | while (ogg_stream_flush(&os, &og)) { |
| 258 | writeOggPage(&og, _fileOs); |
| 259 | } |
| 260 | } else { |
| 261 | ogg_stream_flush(&os, &og); |
| 262 | } |
| 263 |
| 264 | if (_encoder) { |
| 265 | opus_encoder_destroy(_encoder); |
| 266 | _encoder = 0; |
| 267 | } |
| 268 |
| 269 | ogg_stream_clear(&os); |
| 270 |
| 271 | if (_packet) { |
| 272 | free(_packet); |
| 273 | _packet = 0; |
| 274 | } |
| 275 |
| 276 | if (_fileOs) { |
| 277 | fclose(_fileOs); |
| 278 | _fileOs = 0; |
| 279 | } |
| 280 |
| 281 | _packetId = -1; |
| 282 | bytes_written = 0; |
| 283 | pages_out = 0; |
| 284 | total_samples = 0; |
| 285 | enc_granulepos = 0; |
| 286 | size_segments = 0; |
| 287 | last_segments = 0; |
| 288 | last_granulepos = 0; |
| 289 | if (_filePath) { |
| 290 | free(_filePath); |
| 291 | _filePath = 0; |
| 292 | } |
| 293 | memset(&os, 0, sizeof(ogg_stream_state)); |
| 294 | memset(&inopt, 0, sizeof(oe_enc_opt)); |
| 295 | memset(&header, 0, sizeof(OpusHeader)); |
| 296 | memset(&op, 0, sizeof(ogg_packet)); |
| 297 | memset(&og, 0, sizeof(ogg_page)); |
| 298 | } |
| 299 |
| 300 | int initRecorder(const char *path, opus_int32 sampleRate) { |
| 301 | cleanupRecorder(); |
| 302 |
| 303 | coding_rate = sampleRate; |
| 304 | rate = sampleRate; |
| 305 |
| 306 | if (!path) { |
| 307 | LOGE("path is null"); |
| 308 | return 0; |
| 309 | } |
| 310 |
| 311 | int length = strlen(path); |
| 312 | _filePath = (char*) malloc(length + 1); |
| 313 | strcpy(_filePath, path); |
| 314 |
| 315 | _fileOs = fopen(path, "w"); |
| 316 | if (!_fileOs) { |
| 317 | LOGE("error cannot open file: %s", path); |
| 318 | return 0; |
| 319 | } |
| 320 |
| 321 | inopt.rate = rate; |
| 322 | inopt.gain = 0; |
| 323 | inopt.endianness = 0; |
| 324 | inopt.copy_comments = 0; |
| 325 | inopt.rawmode = 0; |
| 326 | inopt.ignorelength = 0; |
| 327 | inopt.samplesize = 16; |
| 328 | inopt.channels = 1; |
| 329 | inopt.skip = 0; |
| 330 |
| 331 | comment_init(&inopt.comments, &inopt.comments_length, opus_get_version_string()); |
| 332 |
| 333 | if (rate != coding_rate) { |
| 334 | LOGE("Invalid rate"); |
| 335 | return 0; |
| 336 | } |
| 337 |
| 338 | header.channels = 1; |
| 339 | header.channel_mapping = 0; |
| 340 | header.input_sample_rate = rate; |
| 341 | header.gain = inopt.gain; |
| 342 | header.nb_streams = 1; |
| 343 |
| 344 | int result = OPUS_OK; |
| 345 | _encoder = opus_encoder_create(coding_rate, 1, OPUS_APPLICATION_VOIP, &result); |
| 346 | if (result != OPUS_OK) { |
| 347 | LOGE("Error cannot create encoder: %s", opus_strerror(result)); |
| 348 | return 0; |
| 349 | } |
| 350 |
| 351 | min_bytes = max_frame_bytes = (1275 * 3 + 7) * header.nb_streams; |
| 352 | _packet = malloc(max_frame_bytes); |
| 353 |
| 354 | result = opus_encoder_ctl(_encoder, OPUS_SET_BITRATE(bitrate)); |
| 355 | //result = opus_encoder_ctl(_encoder, OPUS_SET_COMPLEXITY(10)); |
| 356 | if (result != OPUS_OK) { |
| 357 | LOGE("Error OPUS_SET_BITRATE returned: %s", opus_strerror(result)); |
| 358 | return 0; |
| 359 | } |
| 360 |
| 361 | #ifdef OPUS_SET_LSB_DEPTH |
| 362 | result = opus_encoder_ctl(_encoder, OPUS_SET_LSB_DEPTH(MAX(8, MIN(24, inopt.samplesize)))); |
| 363 | if (result != OPUS_OK) { |
| 364 | LOGE("Warning OPUS_SET_LSB_DEPTH returned: %s", opus_strerror(result)); |
| 365 | } |
| 366 | #endif |
| 367 |
| 368 | opus_int32 lookahead; |
| 369 | result = opus_encoder_ctl(_encoder, OPUS_GET_LOOKAHEAD(&lookahead)); |
| 370 | if (result != OPUS_OK) { |
| 371 | LOGE("Error OPUS_GET_LOOKAHEAD returned: %s", opus_strerror(result)); |
| 372 | return 0; |
| 373 | } |
| 374 |
| 375 | inopt.skip += lookahead; |
| 376 | header.preskip = (int)(inopt.skip * (48000.0 / coding_rate)); |
| 377 | inopt.extraout = (int)(header.preskip * (rate / 48000.0)); |
| 378 |
| 379 | if (ogg_stream_init(&os, serialno = rand()) == -1) { |
| 380 | LOGE("Error: stream init failed"); |
| 381 | return 0; |
| 382 | } |
| 383 |
| 384 | unsigned char header_data[100]; |
| 385 | int packet_size = opus_header_to_packet(&header, header_data, 100); |
| 386 | op.packet = header_data; |
| 387 | op.bytes = packet_size; |
| 388 | op.b_o_s = 1; |
| 389 | op.e_o_s = 0; |
| 390 | op.granulepos = 0; |
| 391 | op.packetno = 0; |
| 392 | ogg_stream_packetin(&os, &op); |
| 393 |
| 394 | while ((result = ogg_stream_flush(&os, &og))) { |
| 395 | if (!result) { |
| 396 | break; |
| 397 | } |
| 398 |
| 399 | int pageBytesWritten = writeOggPage(&og, _fileOs); |
| 400 | if (pageBytesWritten != og.header_len + og.body_len) { |
| 401 | LOGE("Error: failed writing header to output stream"); |
| 402 | return 0; |
| 403 | } |
| 404 | bytes_written += pageBytesWritten; |
| 405 | pages_out++; |
| 406 | } |
| 407 |
| 408 | comment_pad(&inopt.comments, &inopt.comments_length, comment_padding); |
| 409 | op.packet = (unsigned char *)inopt.comments; |
| 410 | op.bytes = inopt.comments_length; |
| 411 | op.b_o_s = 0; |
| 412 | op.e_o_s = 0; |
| 413 | op.granulepos = 0; |
| 414 | op.packetno = 1; |
| 415 | ogg_stream_packetin(&os, &op); |
| 416 |
| 417 | while ((result = ogg_stream_flush(&os, &og))) { |
| 418 | if (result == 0) { |
| 419 | break; |
| 420 | } |
| 421 |
| 422 | int writtenPageBytes = writeOggPage(&og, _fileOs); |
| 423 | if (writtenPageBytes != og.header_len + og.body_len) { |
| 424 | LOGE("Error: failed writing header to output stream"); |
| 425 | return 0; |
| 426 | } |
| 427 |
| 428 | bytes_written += writtenPageBytes; |
| 429 | pages_out++; |
| 430 | } |
| 431 |
| 432 | free(inopt.comments); |
| 433 |
| 434 | return 1; |
| 435 | } |
| 436 |
| 437 | int writeFrame(uint8_t *framePcmBytes, uint32_t frameByteCount, int end) { |
| 438 | size_t cur_frame_size = frame_size; |
| 439 | _packetId++; |
| 440 |
| 441 | opus_int32 nb_samples = frameByteCount / 2; |
| 442 | total_samples += nb_samples; |
| 443 | op.e_o_s = end; |
| 444 |
| 445 | int nbBytes = 0; |
| 446 |
| 447 | if (nb_samples != 0) { |
| 448 | uint8_t *paddedFrameBytes = framePcmBytes; |
| 449 | int freePaddedFrameBytes = 0; |
| 450 |
| 451 | if (nb_samples < cur_frame_size) { |
| 452 | paddedFrameBytes = malloc(cur_frame_size * 2); |
| 453 | freePaddedFrameBytes = 1; |
| 454 | memcpy(paddedFrameBytes, framePcmBytes, frameByteCount); |
| 455 | memset(paddedFrameBytes + nb_samples * 2, 0, cur_frame_size * 2 - nb_samples * 2); |
| 456 | } |
| 457 |
| 458 | nbBytes = opus_encode(_encoder, (opus_int16 *)paddedFrameBytes, cur_frame_size, _packet, max_frame_bytes / 10); |
| 459 | if (freePaddedFrameBytes) { |
| 460 | free(paddedFrameBytes); |
| 461 | } |
| 462 |
| 463 | if (nbBytes < 0) { |
| 464 | LOGE("Encoding failed: %s. Aborting.", opus_strerror(nbBytes)); |
| 465 | return 0; |
| 466 | } |
| 467 |
| 468 | enc_granulepos += cur_frame_size * 48000 / coding_rate; |
| 469 | size_segments = (nbBytes + 255) / 255; |
| 470 | min_bytes = MIN(nbBytes, min_bytes); |
| 471 | } |
| 472 |
| 473 | while ((((size_segments <= 255) && (last_segments + size_segments > 255)) || (enc_granulepos - last_granulepos > max_ogg_delay)) && ogg_stream_flush_fill(&os, &og, 255 * 255)) { |
| 474 | if (ogg_page_packets(&og) != 0) { |
| 475 | last_granulepos = ogg_page_granulepos(&og); |
| 476 | } |
| 477 |
| 478 | last_segments -= og.header[26]; |
| 479 | int writtenPageBytes = writeOggPage(&og, _fileOs); |
| 480 | if (writtenPageBytes != og.header_len + og.body_len) { |
| 481 | LOGE("Error: failed writing data to output stream"); |
| 482 | return 0; |
| 483 | } |
| 484 | bytes_written += writtenPageBytes; |
| 485 | pages_out++; |
| 486 | } |
| 487 |
| 488 | op.packet = _packet; |
| 489 | op.bytes = nbBytes; |
| 490 | op.b_o_s = 0; |
| 491 | op.granulepos = enc_granulepos; |
| 492 | if (op.e_o_s) { |
| 493 | op.granulepos = ((total_samples * 48000 + rate - 1) / rate) + header.preskip; |
| 494 | } |
| 495 | op.packetno = 2 + _packetId; |
| 496 | ogg_stream_packetin(&os, &op); |
| 497 | last_segments += size_segments; |
| 498 |
| 499 | 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)) { |
| 500 | if (ogg_page_packets(&og) != 0) { |
| 501 | last_granulepos = ogg_page_granulepos(&og); |
| 502 | } |
| 503 | last_segments -= og.header[26]; |
| 504 | int writtenPageBytes = writeOggPage(&og, _fileOs); |
| 505 | if (writtenPageBytes != og.header_len + og.body_len) { |
| 506 | LOGE("Error: failed writing data to output stream"); |
| 507 | return 0; |
| 508 | } |
| 509 | bytes_written += writtenPageBytes; |
| 510 | pages_out++; |
| 511 | } |
| 512 |
| 513 | return 1; |
| 514 | } |
| 515 |
| 516 | JNIEXPORT jint Java_org_telegram_messenger_MediaController_startRecord(JNIEnv *env, jclass class, jstring path, jint sampleRate) { |
| 517 | const char *pathStr = (*env)->GetStringUTFChars(env, path, 0); |
| 518 |
| 519 | int32_t result = initRecorder(pathStr, sampleRate); |
| 520 |
| 521 | if (pathStr != 0) { |
| 522 | (*env)->ReleaseStringUTFChars(env, path, pathStr); |
| 523 | } |
| 524 |
| 525 | return result; |
| 526 | } |
| 527 |
| 528 | JNIEXPORT jint Java_org_telegram_messenger_MediaController_writeFrame(JNIEnv *env, jclass class, jobject frame, jint len) { |
| 529 | jbyte *frameBytes = (*env)->GetDirectBufferAddress(env, frame); |
| 530 | return writeFrame((uint8_t *) frameBytes, (uint32_t) len, len / 2 < frame_size); |
| 531 | } |
| 532 |
| 533 | JNIEXPORT void Java_org_telegram_messenger_MediaController_stopRecord(JNIEnv *env, jclass class) { |
| 534 | cleanupRecorder(); |
| 535 | } |
| 536 |
| 537 | JNIEXPORT jint Java_org_telegram_messenger_MediaController_isOpusFile(JNIEnv *env, jclass class, jstring path) { |
| 538 | const char *pathStr = (*env)->GetStringUTFChars(env, path, 0); |
| 539 |
| 540 | int32_t result = 0; |
| 541 |
| 542 | int32_t error = OPUS_OK; |
| 543 | OggOpusFile *file = op_test_file(pathStr, &error); |
| 544 | if (file != NULL) { |
| 545 | error = op_test_open(file); |
| 546 | op_free(file); |
| 547 | result = error == OPUS_OK; |
| 548 | } |
| 549 |
| 550 | if (pathStr != 0) { |
| 551 | (*env)->ReleaseStringUTFChars(env, path, pathStr); |
| 552 | } |
| 553 |
| 554 | return result; |
| 555 | } |
| 556 |
| 557 | static inline void set_bits(uint8_t *bytes, int32_t bitOffset, int32_t value) { |
| 558 | bytes += bitOffset / 8; |
| 559 | bitOffset %= 8; |
| 560 | *((int32_t *) bytes) |= (value << bitOffset); |
| 561 | } |
| 562 |
| 563 | JNIEXPORT jbyteArray Java_org_telegram_messenger_MediaController_getWaveform2(JNIEnv *env, jclass class, jshortArray array, jint length) { |
| 564 |
| 565 | jshort *sampleBuffer = (*env)->GetShortArrayElements(env, array, 0); |
| 566 |
| 567 | const int32_t resultSamples = 100; |
| 568 | uint16_t *samples = malloc(100 * 2); |
| 569 | uint64_t sampleIndex = 0; |
| 570 | uint16_t peakSample = 0; |
| 571 | int32_t sampleRate = (int32_t) MAX(1, length / resultSamples); |
| 572 | int32_t index = 0; |
| 573 |
| 574 | for (int32_t i = 0; i < length; i++) { |
| 575 | uint16_t sample = (uint16_t) abs(sampleBuffer[i]); |
| 576 | if (sample > peakSample) { |
| 577 | peakSample = sample; |
| 578 | } |
| 579 | if (sampleIndex++ % sampleRate == 0) { |
| 580 | if (index < resultSamples) { |
| 581 | samples[index++] = peakSample; |
| 582 | } |
| 583 | peakSample = 0; |
| 584 | } |
| 585 | } |
| 586 |
| 587 | int64_t sumSamples = 0; |
| 588 | for (int32_t i = 0; i < resultSamples; i++) { |
| 589 | sumSamples += samples[i]; |
| 590 | } |
| 591 | uint16_t peak = (uint16_t) (sumSamples * 1.8f / resultSamples); |
| 592 | if (peak < 2500) { |
| 593 | peak = 2500; |
| 594 | } |
| 595 |
| 596 | for (int32_t i = 0; i < resultSamples; i++) { |
| 597 | uint16_t sample = (uint16_t) ((int64_t) samples[i]); |
| 598 | if (sample > peak) { |
| 599 | samples[i] = peak; |
| 600 | } |
| 601 | } |
| 602 |
| 603 | (*env)->ReleaseShortArrayElements(env, array, sampleBuffer, 0); |
| 604 |
| 605 | uint32_t bitstreamLength = resultSamples * 5 / 8 + 1; |
| 606 | jbyteArray *result = (*env)->NewByteArray(env, bitstreamLength); |
| 607 | if (result) { |
| 608 | uint8_t *bytes = malloc(bitstreamLength + 4); |
| 609 | memset(bytes, 0, bitstreamLength + 4); |
| 610 | for (int32_t i = 0; i < resultSamples; i++) { |
| 611 | int32_t value = MIN(31, abs((int32_t) samples[i]) * 31 / peak); |
| 612 | set_bits(bytes, i * 5, value & 31); |
| 613 | } |
| 614 | (*env)->SetByteArrayRegion(env, result, 0, bitstreamLength, (jbyte *) bytes); |
| 615 | } |
| 616 | free(samples); |
| 617 |
| 618 | return result; |
| 619 | } |
| 620 |
| 621 | int16_t *sampleBuffer = NULL; |
| 622 |
| 623 | JNIEXPORT jbyteArray Java_org_telegram_messenger_MediaController_getWaveform(JNIEnv *env, jclass class, jstring path) { |
| 624 | const char *pathStr = (*env)->GetStringUTFChars(env, path, 0); |
| 625 | jbyteArray result = 0; |
| 626 |
| 627 | int error = OPUS_OK; |
| 628 | OggOpusFile *opusFile = op_open_file(pathStr, &error); |
| 629 | if (opusFile != NULL && error == OPUS_OK) { |
| 630 | int64_t totalSamples = op_pcm_total(opusFile, -1); |
| 631 | const uint32_t resultSamples = 100; |
| 632 | int32_t sampleRate = MAX(1, (int32_t) (totalSamples / resultSamples)); |
| 633 |
| 634 | uint16_t *samples = malloc(100 * 2); |
| 635 |
| 636 | size_t bufferSize = 1024 * 128; |
| 637 | if (sampleBuffer == NULL) { |
| 638 | sampleBuffer = malloc(bufferSize); |
| 639 | } |
| 640 | uint64_t sampleIndex = 0; |
| 641 | uint16_t peakSample = 0; |
| 642 |
| 643 | int32_t index = 0; |
| 644 |
| 645 | while (1) { |
| 646 | int readSamples = op_read(opusFile, sampleBuffer, bufferSize / 2, NULL); |
| 647 | for (int32_t i = 0; i < readSamples; i++) { |
| 648 | uint16_t sample = (uint16_t) abs(sampleBuffer[i]); |
| 649 | if (sample > peakSample) { |
| 650 | peakSample = sample; |
| 651 | } |
| 652 | if (sampleIndex++ % sampleRate == 0) { |
| 653 | if (index < resultSamples) { |
| 654 | samples[index++] = peakSample; |
| 655 | } |
| 656 | peakSample = 0; |
| 657 | } |
| 658 | } |
| 659 | if (readSamples == 0) { |
| 660 | break; |
| 661 | } |
| 662 | } |
| 663 |
| 664 | int64_t sumSamples = 0; |
| 665 | for (int32_t i = 0; i < resultSamples; i++) { |
| 666 | sumSamples += samples[i]; |
| 667 | } |
| 668 | uint16_t peak = (uint16_t) (sumSamples * 1.8f / resultSamples); |
| 669 | if (peak < 2500) { |
| 670 | peak = 2500; |
| 671 | } |
| 672 |
| 673 | for (int32_t i = 0; i < resultSamples; i++) { |
| 674 | uint16_t sample = (uint16_t) ((int64_t) samples[i]); |
| 675 | if (sample > peak) { |
| 676 | samples[i] = peak; |
| 677 | } |
| 678 | } |
| 679 |
| 680 | //free(sampleBuffer); |
| 681 | op_free(opusFile); |
| 682 |
| 683 | uint32_t bitstreamLength = (resultSamples * 5) / 8 + 1; |
| 684 | result = (*env)->NewByteArray(env, bitstreamLength); |
| 685 | if (result) { |
| 686 | uint8_t *bytes = malloc(bitstreamLength + 4); |
| 687 | memset(bytes, 0, bitstreamLength + 4); |
| 688 |
| 689 | for (int32_t i = 0; i < resultSamples; i++) { |
| 690 | int32_t value = MIN(31, abs((int32_t) samples[i]) * 31 / peak); |
| 691 | set_bits(bytes, i * 5, value & 31); |
| 692 | } |
| 693 |
| 694 | (*env)->SetByteArrayRegion(env, result, 0, bitstreamLength, (jbyte *) bytes); |
| 695 | } |
| 696 | free(samples); |
| 697 | } |
| 698 |
| 699 | if (pathStr != 0) { |
| 700 | (*env)->ReleaseStringUTFChars(env, path, pathStr); |
| 701 | } |
| 702 |
| 703 | return result; |
| 704 | } |
| 705 |
| 706 | JNIEXPORT void JNICALL Java_org_telegram_ui_Stories_recorder_FfmpegAudioWaveformLoader_init(JNIEnv *env, jobject obj, jstring pathJStr, jint count) { |
| 707 | const char *path = (*env)->GetStringUTFChars(env, pathJStr, 0); |
| 708 |
| 709 | AVFormatContext *formatContext = avformat_alloc_context(); |
| 710 | if (!formatContext) { |
| 711 | // Handle error |
| 712 | return; |
| 713 | } |
| 714 |
| 715 | int res; |
| 716 | if ((res = avformat_open_input(&formatContext, path, NULL, NULL)) != 0) { |
| 717 | LOGD("avformat_open_input error %s", av_err2str(res)); |
| 718 | // Handle error |
| 719 | avformat_free_context(formatContext); |
| 720 | return; |
| 721 | } |
| 722 |
| 723 | if (avformat_find_stream_info(formatContext, NULL) < 0) { |
| 724 | // Handle error |
| 725 | avformat_close_input(&formatContext); |
| 726 | return; |
| 727 | } |
| 728 |
| 729 | AVCodec *codec = NULL; |
| 730 | int audioStreamIndex = av_find_best_stream(formatContext, AVMEDIA_TYPE_AUDIO, -1, -1, &codec, 0); |
| 731 | if (audioStreamIndex < 0) { |
| 732 | LOGD("av_find_best_stream error %s", av_err2str(audioStreamIndex)); |
| 733 | // Handle error |
| 734 | avformat_close_input(&formatContext); |
| 735 | return; |
| 736 | } |
| 737 |
| 738 | AVCodecContext *codecContext = avcodec_alloc_context3(codec); |
| 739 | avcodec_parameters_to_context(codecContext, formatContext->streams[audioStreamIndex]->codecpar); |
| 740 |
| 741 | int64_t duration_in_microseconds = formatContext->duration; |
| 742 | double duration_in_seconds = (double)duration_in_microseconds / AV_TIME_BASE; |
| 743 |
| 744 | if (avcodec_open2(codecContext, codec, NULL) < 0) { |
| 745 | // Handle error |
| 746 | avcodec_free_context(&codecContext); |
| 747 | avformat_close_input(&formatContext); |
| 748 | return; |
| 749 | } |
| 750 |
| 751 | // Obtain the class and method to callback |
| 752 | jclass cls = (*env)->GetObjectClass(env, obj); |
| 753 | jmethodID mid = (*env)->GetMethodID(env, cls, "receiveChunk", "([SI)V"); |
| 754 |
| 755 | AVFrame *frame = av_frame_alloc(); |
| 756 | AVPacket packet; |
| 757 |
| 758 | int sampleRate = codecContext->sample_rate; // Sample rate from FFmpeg's codec context |
| 759 | int skip = 4; |
| 760 | int barWidth = (int) round((double) duration_in_seconds * sampleRate / count / (1 + skip)); // Assuming you have 'duration' and 'count' defined somewhere |
| 761 |
| 762 | int channels = codecContext->ch_layout.nb_channels; |
| 763 |
| 764 | short peak = 0; |
| 765 | int currentCount = 0; |
| 766 | int index = 0; |
| 767 | int chunkIndex = 0; |
| 768 | short waveformChunkData[32]; // Allocate the chunk array |
| 769 |
| 770 | while (av_read_frame(formatContext, &packet) >= 0) { |
| 771 | if (packet.stream_index == audioStreamIndex) { |
| 772 | // Decode the audio packet |
| 773 | int response = avcodec_send_packet(codecContext, &packet); |
| 774 |
| 775 | while (response >= 0) { |
| 776 | response = avcodec_receive_frame(codecContext, frame); |
| 777 | if (response == AVERROR(EAGAIN) || response == AVERROR_EOF) { |
| 778 | break; |
| 779 | } else if (response < 0) { |
| 780 | // Handle error |
| 781 | break; |
| 782 | } |
| 783 |
| 784 | const int is_planar = av_sample_fmt_is_planar(codecContext->sample_fmt); |
| 785 | const int sample_size = av_get_bytes_per_sample(codecContext->sample_fmt); |
| 786 | for (int i = 0; i < frame->nb_samples; i++) { |
| 787 | int sum = 0; |
| 788 | for (int channel = 0; channel < channels; channel++) { |
| 789 | uint8_t *data; |
| 790 | if (is_planar) { |
| 791 | data = frame->data[channel] + i * sample_size; |
| 792 | } else { |
| 793 | data = frame->data[0] + (i * channels + channel) * sample_size; |
| 794 | } |
| 795 | short sample_value = 0; |
| 796 | switch (codecContext->sample_fmt) { |
| 797 | case AV_SAMPLE_FMT_S16: |
| 798 | case AV_SAMPLE_FMT_S16P: |
| 799 | // Signed 16-bit PCM |
| 800 | sample_value = *(int16_t *)data; |
| 801 | break; |
| 802 |
| 803 | case AV_SAMPLE_FMT_FLT: |
| 804 | case AV_SAMPLE_FMT_FLTP: |
| 805 | // 32-bit float, scale to 16-bit PCM range |
| 806 | sample_value = (short)(*(float *)data * 32767.0f); |
| 807 | break; |
| 808 |
| 809 | case AV_SAMPLE_FMT_U8: |
| 810 | case AV_SAMPLE_FMT_U8P: |
| 811 | // Unsigned 8-bit PCM, scale to 16-bit PCM range |
| 812 | sample_value = (*(uint8_t *)data - 128) * 256; |
| 813 | break; |
| 814 |
| 815 | default: |
| 816 | break; |
| 817 | } |
| 818 | sum += sample_value; |
| 819 | } |
| 820 | short value = sum / channels; |
| 821 |
| 822 | if (currentCount >= barWidth) { |
| 823 | waveformChunkData[index - chunkIndex] = peak; |
| 824 | index++; |
| 825 | if (index - chunkIndex >= sizeof(waveformChunkData) / sizeof(short) || index >= count) { |
| 826 | jshortArray waveformData = (*env)->NewShortArray(env, sizeof(waveformChunkData) / sizeof(short)); |
| 827 | (*env)->SetShortArrayRegion(env, waveformData, 0, sizeof(waveformChunkData) / sizeof(short), waveformChunkData); |
| 828 | (*env)->CallVoidMethod(env, obj, mid, waveformData, sizeof(waveformChunkData) / sizeof(short)); |
| 829 |
| 830 | // Reset the chunk data |
| 831 | memset(waveformChunkData, 0, sizeof(waveformChunkData)); |
| 832 | chunkIndex = index; |
| 833 |
| 834 | // Delete local reference to avoid memory leak |
| 835 | (*env)->DeleteLocalRef(env, waveformData); |
| 836 | } |
| 837 | peak = 0; |
| 838 | currentCount = 0; |
| 839 | if (index >= count) { |
| 840 | break; |
| 841 | } |
| 842 | } |
| 843 |
| 844 | if (peak < value) { |
| 845 | peak = value; |
| 846 | } |
| 847 | currentCount++; |
| 848 |
| 849 | // Skip logic |
| 850 | i += skip; |
| 851 | if (i >= frame->nb_samples) { |
| 852 | break; |
| 853 | } |
| 854 | } |
| 855 | } |
| 856 | } |
| 857 |
| 858 | av_packet_unref(&packet); |
| 859 |
| 860 | if (index >= count) { |
| 861 | break; |
| 862 | } |
| 863 |
| 864 | // Check for stopping flag |
| 865 | jfieldID fid = (*env)->GetFieldID(env, cls, "running", "Z"); |
| 866 | jboolean running = (*env)->GetBooleanField(env, obj, fid); |
| 867 | if (running == JNI_FALSE) { |
| 868 | break; |
| 869 | } |
| 870 | } |
| 871 |
| 872 | av_frame_free(&frame); |
| 873 | avcodec_free_context(&codecContext); |
| 874 | avformat_close_input(&formatContext); |
| 875 |
| 876 | (*env)->ReleaseStringUTFChars(env, pathJStr, path); |
| 877 | } |
| 878 |
| 879 | int cropOpusAudio(const char *inputPath, const char *outputPath, float startTimeMs, float endTimeMs) { |
| 880 | int error; |
| 881 | OggOpusFile *opusFile = op_open_file(inputPath, &error); |
| 882 | if (!opusFile || error != OPUS_OK) { |
| 883 | LOGE("Failed to open input opus file: %s", opus_strerror(error)); |
| 884 | return 0; |
| 885 | } |
| 886 |
| 887 | const OpusHead *head = op_head(opusFile, -1); |
| 888 | if (!head) { |
| 889 | LOGE("Failed to read Opus header"); |
| 890 | op_free(opusFile); |
| 891 | return 0; |
| 892 | } |
| 893 |
| 894 | int channels = head->channel_count; |
| 895 | opus_int64 total_source_samples = op_pcm_total(opusFile, -1); |
| 896 | opus_int32 rate = 48000; |
| 897 |
| 898 | opus_int64 start_sample = MAX(0, MIN(total_source_samples, (opus_int64) ((startTimeMs / 1000.0) * rate))); |
| 899 | opus_int64 end_sample = MAX(0, MIN(total_source_samples, (opus_int64) ((endTimeMs / 1000.0) * rate))); |
| 900 | opus_int64 crop_length = end_sample - start_sample; |
| 901 |
| 902 | if (start_sample >= total_source_samples || end_sample > total_source_samples || start_sample >= end_sample) { |
| 903 | LOGE("Invalid crop range"); |
| 904 | op_free(opusFile); |
| 905 | return 0; |
| 906 | } |
| 907 |
| 908 | if (op_pcm_seek(opusFile, start_sample) != 0) { |
| 909 | LOGE("Failed to seek to start sample"); |
| 910 | op_free(opusFile); |
| 911 | return 0; |
| 912 | } |
| 913 |
| 914 | if (!initRecorder(outputPath, rate)) { |
| 915 | LOGE("Failed to init recorder"); |
| 916 | op_free(opusFile); |
| 917 | return 0; |
| 918 | } |
| 919 |
| 920 | int16_t *buffer = malloc(sizeof(int16_t) * frame_size * channels); |
| 921 | if (!buffer) { |
| 922 | LOGE("Out of memory"); |
| 923 | cleanupRecorder(); |
| 924 | op_free(opusFile); |
| 925 | return 0; |
| 926 | } |
| 927 |
| 928 | opus_int64 remaining_samples = crop_length; |
| 929 | while (remaining_samples > 0) { |
| 930 | int max_samples = (int) MIN(960, remaining_samples / channels); |
| 931 | if (max_samples <= 0) break; |
| 932 |
| 933 | int samples_read = op_read(opusFile, buffer, max_samples * channels, NULL); |
| 934 | if (samples_read <= 0) break; |
| 935 | remaining_samples -= samples_read; |
| 936 |
| 937 | int end = remaining_samples <= 0; |
| 938 |
| 939 | size_t byte_count = samples_read * sizeof(int16_t); |
| 940 | if (!writeFrame((uint8_t *)buffer, byte_count, end)) { |
| 941 | LOGE("Failed to write frame"); |
| 942 | free(buffer); |
| 943 | cleanupRecorder(); |
| 944 | op_free(opusFile); |
| 945 | return 0; |
| 946 | } |
| 947 | } |
| 948 |
| 949 | free(buffer); |
| 950 | cleanupRecorder(); |
| 951 | op_free(opusFile); |
| 952 | return 1; |
| 953 | } |
| 954 |
| 955 | int append_stream(OggOpusFile *of, int16_t* buffer, int channels, int is_last) { |
| 956 | opus_int64 total_source_samples = op_pcm_total(of, -1); |
| 957 | while (total_source_samples > 0) { |
| 958 | int samples_read = op_read(of, buffer, frame_size, NULL); |
| 959 | if (samples_read < 0) { |
| 960 | LOGE("Decoding error from op_read(): %d", samples_read); |
| 961 | return 0; |
| 962 | } |
| 963 | if (samples_read == 0) { |
| 964 | break; |
| 965 | } |
| 966 | total_source_samples -= samples_read; |
| 967 | size_t byte_count = (size_t) samples_read * channels * sizeof(int16_t); |
| 968 | if (!writeFrame((uint8_t*) buffer, byte_count, is_last && total_source_samples <= 0)) { |
| 969 | LOGE("Failed to write encoded frame"); |
| 970 | return 0; |
| 971 | } |
| 972 | } |
| 973 | return 1; |
| 974 | } |
| 975 |
| 976 | int joinOpusAudios(const char* file1, const char* file2, const char* dest) { |
| 977 | int error; |
| 978 | OggOpusFile *opusFile1 = op_open_file(file1, &error); |
| 979 | if (!opusFile1 || error != OPUS_OK) { |
| 980 | LOGE("Failed to open input opus file1: %s", opus_strerror(error)); |
| 981 | return 0; |
| 982 | } |
| 983 | OggOpusFile *opusFile2 = op_open_file(file2, &error); |
| 984 | if (!opusFile2 || error != OPUS_OK) { |
| 985 | LOGE("Failed to open input opus file2: %s", opus_strerror(error)); |
| 986 | return 0; |
| 987 | } |
| 988 |
| 989 | const OpusHead *head1 = op_head(opusFile1, -1); |
| 990 | if (!head1) { |
| 991 | LOGE("Failed to read Opus header"); |
| 992 | op_free(opusFile1); |
| 993 | op_free(opusFile2); |
| 994 | return 0; |
| 995 | } |
| 996 | const OpusHead *head2 = op_head(opusFile2, -1); |
| 997 | if (!head2) { |
| 998 | LOGE("Failed to read Opus header"); |
| 999 | op_free(opusFile1); |
| 1000 | op_free(opusFile2); |
| 1001 | return 0; |
| 1002 | } |
| 1003 |
| 1004 | int channels = MIN(head1->channel_count, head2->channel_count); |
| 1005 | opus_int32 rate = 48000; |
| 1006 |
| 1007 | if (!initRecorder(dest, rate)) { |
| 1008 | LOGE("Failed to init recorder"); |
| 1009 | op_free(opusFile1); |
| 1010 | op_free(opusFile2); |
| 1011 | return 0; |
| 1012 | } |
| 1013 |
| 1014 | int16_t *buffer = malloc(sizeof(int16_t) * frame_size * channels); |
| 1015 | if (!buffer) { |
| 1016 | LOGE("Out of memory"); |
| 1017 | cleanupRecorder(); |
| 1018 | op_free(opusFile1); |
| 1019 | op_free(opusFile2); |
| 1020 | return 0; |
| 1021 | } |
| 1022 |
| 1023 | append_stream(opusFile1, buffer, channels, 0); |
| 1024 | append_stream(opusFile2, buffer, channels, 1); |
| 1025 |
| 1026 | free(buffer); |
| 1027 | cleanupRecorder(); |
| 1028 | op_free(opusFile1); |
| 1029 | op_free(opusFile2); |
| 1030 |
| 1031 | return 1; |
| 1032 | } |
| 1033 |
| 1034 | JNIEXPORT jboolean Java_org_telegram_messenger_MediaController_cropOpusFile(JNIEnv *env, jclass class, jstring src, jstring dst, jlong startMs, jlong endMs) { |
| 1035 | const char* srcStr = (*env)->GetStringUTFChars(env, src, 0); |
| 1036 | const char* dstStr = (*env)->GetStringUTFChars(env, dst, 0); |
| 1037 | int result = cropOpusAudio(srcStr, dstStr, startMs, endMs); |
| 1038 | (*env)->ReleaseStringUTFChars(env, src, srcStr); |
| 1039 | (*env)->ReleaseStringUTFChars(env, dst, dstStr); |
| 1040 | return result == 1; |
| 1041 | } |
| 1042 |
| 1043 | JNIEXPORT jboolean Java_org_telegram_messenger_MediaController_joinOpusFiles(JNIEnv* env, jclass class, jstring file1, jstring file2, jstring dest) { |
| 1044 | const char* file1Str = (*env)->GetStringUTFChars(env, file1, 0); |
| 1045 | const char* file2Str = (*env)->GetStringUTFChars(env, file2, 0); |
| 1046 | const char* destStr = (*env)->GetStringUTFChars(env, dest, 0); |
| 1047 | int result = joinOpusAudios(file1Str, file2Str, destStr); |
| 1048 | (*env)->ReleaseStringUTFChars(env, file1, file1Str); |
| 1049 | (*env)->ReleaseStringUTFChars(env, file2, file2Str); |
| 1050 | (*env)->ReleaseStringUTFChars(env, dest, destStr); |
| 1051 | return result == 1; |
| 1052 | } |