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