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