audio.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  1. #include <jni.h>
  2. #include <ogg/ogg.h>
  3. #include <stdio.h>
  4. #include <opus.h>
  5. #include <stdlib.h>
  6. #include <time.h>
  7. #include <opusfile.h>
  8. #include <math.h>
  9. #include "c_utils.h"
  10. typedef struct {
  11. int version;
  12. int channels; /* Number of channels: 1..255 */
  13. int preskip;
  14. ogg_uint32_t input_sample_rate;
  15. int gain; /* in dB S7.8 should be zero whenever possible */
  16. int channel_mapping;
  17. /* The rest is only used if channel_mapping != 0 */
  18. int nb_streams;
  19. int nb_coupled;
  20. unsigned char stream_map[255];
  21. } OpusHeader;
  22. typedef struct {
  23. unsigned char *data;
  24. int maxlen;
  25. int pos;
  26. } Packet;
  27. typedef struct {
  28. const unsigned char *data;
  29. int maxlen;
  30. int pos;
  31. } ROPacket;
  32. typedef struct {
  33. void *readdata;
  34. opus_int64 total_samples_per_channel;
  35. int rawmode;
  36. int channels;
  37. long rate;
  38. int gain;
  39. int samplesize;
  40. int endianness;
  41. char *infilename;
  42. int ignorelength;
  43. int skip;
  44. int extraout;
  45. char *comments;
  46. int comments_length;
  47. int copy_comments;
  48. } oe_enc_opt;
  49. static int write_uint32(Packet *p, ogg_uint32_t val) {
  50. if (p->pos > p->maxlen - 4) {
  51. return 0;
  52. }
  53. p->data[p->pos ] = (val ) & 0xFF;
  54. p->data[p->pos+1] = (val>> 8) & 0xFF;
  55. p->data[p->pos+2] = (val>>16) & 0xFF;
  56. p->data[p->pos+3] = (val>>24) & 0xFF;
  57. p->pos += 4;
  58. return 1;
  59. }
  60. static int write_uint16(Packet *p, ogg_uint16_t val) {
  61. if (p->pos > p->maxlen-2) {
  62. return 0;
  63. }
  64. p->data[p->pos ] = (val ) & 0xFF;
  65. p->data[p->pos+1] = (val>> 8) & 0xFF;
  66. p->pos += 2;
  67. return 1;
  68. }
  69. static int write_chars(Packet *p, const unsigned char *str, int nb_chars)
  70. {
  71. int i;
  72. if (p->pos>p->maxlen-nb_chars)
  73. return 0;
  74. for (i=0;i<nb_chars;i++)
  75. p->data[p->pos++] = str[i];
  76. return 1;
  77. }
  78. static int read_uint32(ROPacket *p, ogg_uint32_t *val)
  79. {
  80. if (p->pos>p->maxlen-4)
  81. return 0;
  82. *val = (ogg_uint32_t)p->data[p->pos ];
  83. *val |= (ogg_uint32_t)p->data[p->pos+1]<< 8;
  84. *val |= (ogg_uint32_t)p->data[p->pos+2]<<16;
  85. *val |= (ogg_uint32_t)p->data[p->pos+3]<<24;
  86. p->pos += 4;
  87. return 1;
  88. }
  89. static int read_uint16(ROPacket *p, ogg_uint16_t *val)
  90. {
  91. if (p->pos>p->maxlen-2)
  92. return 0;
  93. *val = (ogg_uint16_t)p->data[p->pos ];
  94. *val |= (ogg_uint16_t)p->data[p->pos+1]<<8;
  95. p->pos += 2;
  96. return 1;
  97. }
  98. static int read_chars(ROPacket *p, unsigned char *str, int nb_chars)
  99. {
  100. int i;
  101. if (p->pos>p->maxlen-nb_chars)
  102. return 0;
  103. for (i=0;i<nb_chars;i++)
  104. str[i] = p->data[p->pos++];
  105. return 1;
  106. }
  107. int opus_header_to_packet(const OpusHeader *h, unsigned char *packet, int len) {
  108. int i;
  109. Packet p;
  110. unsigned char ch;
  111. p.data = packet;
  112. p.maxlen = len;
  113. p.pos = 0;
  114. if (len < 19) {
  115. return 0;
  116. }
  117. if (!write_chars(&p, (const unsigned char *)"OpusHead", 8)) {
  118. return 0;
  119. }
  120. ch = 1;
  121. if (!write_chars(&p, &ch, 1)) {
  122. return 0;
  123. }
  124. ch = h->channels;
  125. if (!write_chars(&p, &ch, 1)) {
  126. return 0;
  127. }
  128. if (!write_uint16(&p, h->preskip)) {
  129. return 0;
  130. }
  131. if (!write_uint32(&p, h->input_sample_rate)) {
  132. return 0;
  133. }
  134. if (!write_uint16(&p, h->gain)) {
  135. return 0;
  136. }
  137. ch = h->channel_mapping;
  138. if (!write_chars(&p, &ch, 1)) {
  139. return 0;
  140. }
  141. if (h->channel_mapping != 0) {
  142. ch = h->nb_streams;
  143. if (!write_chars(&p, &ch, 1)) {
  144. return 0;
  145. }
  146. ch = h->nb_coupled;
  147. if (!write_chars(&p, &ch, 1)) {
  148. return 0;
  149. }
  150. /* Multi-stream support */
  151. for (i = 0; i < h->channels; i++) {
  152. if (!write_chars(&p, &h->stream_map[i], 1)) {
  153. return 0;
  154. }
  155. }
  156. }
  157. return p.pos;
  158. }
  159. #define writeint(buf, base, val) do { buf[base + 3] = ((val) >> 24) & 0xff; \
  160. buf[base + 2]=((val) >> 16) & 0xff; \
  161. buf[base + 1]=((val) >> 8) & 0xff; \
  162. buf[base] = (val) & 0xff; \
  163. } while(0)
  164. static void comment_init(char **comments, int *length, const char *vendor_string) {
  165. // The 'vendor' field should be the actual encoding library used
  166. size_t vendor_length = strlen(vendor_string);
  167. int user_comment_list_length = 0;
  168. size_t len = 8 + 4 + vendor_length + 4;
  169. char *p = (char *)malloc(len);
  170. memcpy(p, "OpusTags", 8);
  171. writeint(p, 8, vendor_length);
  172. memcpy(p + 12, vendor_string, vendor_length);
  173. writeint(p, 12 + vendor_length, user_comment_list_length);
  174. *length = len;
  175. *comments = p;
  176. }
  177. static void comment_pad(char **comments, int* length, size_t amount) {
  178. if (amount > 0) {
  179. char *p = *comments;
  180. // Make sure there is at least amount worth of padding free, and round up to the maximum that fits in the current ogg segments
  181. size_t newlen = (*length + amount + 255) / 255 * 255 - 1;
  182. p = realloc(p, newlen);
  183. for (int32_t i = *length; i < newlen; i++) {
  184. p[i] = 0;
  185. }
  186. *comments = p;
  187. *length = newlen;
  188. }
  189. }
  190. static int writeOggPage(ogg_page *page, FILE *os) {
  191. int written = fwrite(page->header, sizeof(unsigned char), (size_t) page->header_len, os);
  192. written += fwrite(page->body, sizeof(unsigned char), (size_t) page->body_len, os);
  193. return written;
  194. }
  195. const opus_int32 bitrate = OPUS_BITRATE_MAX;
  196. const opus_int32 frame_size = 960;
  197. const int with_cvbr = 1;
  198. const int max_ogg_delay = 0;
  199. const int comment_padding = 512;
  200. opus_int32 rate = 48000;
  201. opus_int32 coding_rate = 48000;
  202. ogg_int32_t _packetId;
  203. OpusEncoder *_encoder = 0;
  204. uint8_t *_packet = 0;
  205. ogg_stream_state os;
  206. FILE *_fileOs = 0;
  207. oe_enc_opt inopt;
  208. OpusHeader header;
  209. opus_int32 min_bytes;
  210. int max_frame_bytes;
  211. ogg_packet op;
  212. ogg_page og;
  213. opus_int64 bytes_written;
  214. opus_int64 pages_out;
  215. opus_int64 total_samples;
  216. ogg_int64_t enc_granulepos;
  217. ogg_int64_t last_granulepos;
  218. int size_segments;
  219. int last_segments;
  220. void cleanupRecorder() {
  221. ogg_stream_flush(&os, &og);
  222. if (_encoder) {
  223. opus_encoder_destroy(_encoder);
  224. _encoder = 0;
  225. }
  226. ogg_stream_clear(&os);
  227. if (_packet) {
  228. free(_packet);
  229. _packet = 0;
  230. }
  231. if (_fileOs) {
  232. fclose(_fileOs);
  233. _fileOs = 0;
  234. }
  235. _packetId = -1;
  236. bytes_written = 0;
  237. pages_out = 0;
  238. total_samples = 0;
  239. enc_granulepos = 0;
  240. size_segments = 0;
  241. last_segments = 0;
  242. last_granulepos = 0;
  243. memset(&os, 0, sizeof(ogg_stream_state));
  244. memset(&inopt, 0, sizeof(oe_enc_opt));
  245. memset(&header, 0, sizeof(OpusHeader));
  246. memset(&op, 0, sizeof(ogg_packet));
  247. memset(&og, 0, sizeof(ogg_page));
  248. }
  249. int initRecorder(const char *path, opus_int32 sampleRate) {
  250. cleanupRecorder();
  251. coding_rate = sampleRate;
  252. rate = sampleRate;
  253. if (!path) {
  254. return 0;
  255. }
  256. _fileOs = fopen(path, "wb");
  257. if (!_fileOs) {
  258. return 0;
  259. }
  260. inopt.rate = rate;
  261. inopt.gain = 0;
  262. inopt.endianness = 0;
  263. inopt.copy_comments = 0;
  264. inopt.rawmode = 0;
  265. inopt.ignorelength = 0;
  266. inopt.samplesize = 16;
  267. inopt.channels = 1;
  268. inopt.skip = 0;
  269. comment_init(&inopt.comments, &inopt.comments_length, opus_get_version_string());
  270. if (rate != coding_rate) {
  271. LOGE("Invalid rate");
  272. return 0;
  273. }
  274. header.channels = 1;
  275. header.channel_mapping = 0;
  276. header.input_sample_rate = rate;
  277. header.gain = inopt.gain;
  278. header.nb_streams = 1;
  279. int result = OPUS_OK;
  280. _encoder = opus_encoder_create(coding_rate, 1, OPUS_APPLICATION_VOIP, &result);
  281. if (result != OPUS_OK) {
  282. LOGE("Error cannot create encoder: %s", opus_strerror(result));
  283. return 0;
  284. }
  285. min_bytes = max_frame_bytes = (1275 * 3 + 7) * header.nb_streams;
  286. _packet = malloc(max_frame_bytes);
  287. result = opus_encoder_ctl(_encoder, OPUS_SET_BITRATE(bitrate));
  288. //result = opus_encoder_ctl(_encoder, OPUS_SET_COMPLEXITY(10));
  289. if (result != OPUS_OK) {
  290. LOGE("Error OPUS_SET_BITRATE returned: %s", opus_strerror(result));
  291. return 0;
  292. }
  293. #ifdef OPUS_SET_LSB_DEPTH
  294. result = opus_encoder_ctl(_encoder, OPUS_SET_LSB_DEPTH(MAX(8, MIN(24, inopt.samplesize))));
  295. if (result != OPUS_OK) {
  296. LOGE("Warning OPUS_SET_LSB_DEPTH returned: %s", opus_strerror(result));
  297. }
  298. #endif
  299. opus_int32 lookahead;
  300. result = opus_encoder_ctl(_encoder, OPUS_GET_LOOKAHEAD(&lookahead));
  301. if (result != OPUS_OK) {
  302. LOGE("Error OPUS_GET_LOOKAHEAD returned: %s", opus_strerror(result));
  303. return 0;
  304. }
  305. inopt.skip += lookahead;
  306. header.preskip = (int)(inopt.skip * (48000.0 / coding_rate));
  307. inopt.extraout = (int)(header.preskip * (rate / 48000.0));
  308. if (ogg_stream_init(&os, rand()) == -1) {
  309. LOGE("Error: stream init failed");
  310. return 0;
  311. }
  312. unsigned char header_data[100];
  313. int packet_size = opus_header_to_packet(&header, header_data, 100);
  314. op.packet = header_data;
  315. op.bytes = packet_size;
  316. op.b_o_s = 1;
  317. op.e_o_s = 0;
  318. op.granulepos = 0;
  319. op.packetno = 0;
  320. ogg_stream_packetin(&os, &op);
  321. while ((result = ogg_stream_flush(&os, &og))) {
  322. if (!result) {
  323. break;
  324. }
  325. int pageBytesWritten = writeOggPage(&og, _fileOs);
  326. if (pageBytesWritten != og.header_len + og.body_len) {
  327. LOGE("Error: failed writing header to output stream");
  328. return 0;
  329. }
  330. bytes_written += pageBytesWritten;
  331. pages_out++;
  332. }
  333. comment_pad(&inopt.comments, &inopt.comments_length, comment_padding);
  334. op.packet = (unsigned char *)inopt.comments;
  335. op.bytes = inopt.comments_length;
  336. op.b_o_s = 0;
  337. op.e_o_s = 0;
  338. op.granulepos = 0;
  339. op.packetno = 1;
  340. ogg_stream_packetin(&os, &op);
  341. while ((result = ogg_stream_flush(&os, &og))) {
  342. if (result == 0) {
  343. break;
  344. }
  345. int writtenPageBytes = writeOggPage(&og, _fileOs);
  346. if (writtenPageBytes != og.header_len + og.body_len) {
  347. LOGE("Error: failed writing header to output stream");
  348. return 0;
  349. }
  350. bytes_written += writtenPageBytes;
  351. pages_out++;
  352. }
  353. free(inopt.comments);
  354. return 1;
  355. }
  356. int writeFrame(uint8_t *framePcmBytes, uint32_t frameByteCount) {
  357. size_t cur_frame_size = frame_size;
  358. _packetId++;
  359. opus_int32 nb_samples = frameByteCount / 2;
  360. total_samples += nb_samples;
  361. if (nb_samples < frame_size) {
  362. op.e_o_s = 1;
  363. } else {
  364. op.e_o_s = 0;
  365. }
  366. int nbBytes = 0;
  367. if (nb_samples != 0) {
  368. uint8_t *paddedFrameBytes = framePcmBytes;
  369. int freePaddedFrameBytes = 0;
  370. if (nb_samples < cur_frame_size) {
  371. paddedFrameBytes = malloc(cur_frame_size * 2);
  372. freePaddedFrameBytes = 1;
  373. memcpy(paddedFrameBytes, framePcmBytes, frameByteCount);
  374. memset(paddedFrameBytes + nb_samples * 2, 0, cur_frame_size * 2 - nb_samples * 2);
  375. }
  376. nbBytes = opus_encode(_encoder, (opus_int16 *)paddedFrameBytes, cur_frame_size, _packet, max_frame_bytes / 10);
  377. if (freePaddedFrameBytes) {
  378. free(paddedFrameBytes);
  379. }
  380. if (nbBytes < 0) {
  381. LOGE("Encoding failed: %s. Aborting.", opus_strerror(nbBytes));
  382. return 0;
  383. }
  384. enc_granulepos += cur_frame_size * 48000 / coding_rate;
  385. size_segments = (nbBytes + 255) / 255;
  386. min_bytes = MIN(nbBytes, min_bytes);
  387. }
  388. while ((((size_segments <= 255) && (last_segments + size_segments > 255)) || (enc_granulepos - last_granulepos > max_ogg_delay)) && ogg_stream_flush_fill(&os, &og, 255 * 255)) {
  389. if (ogg_page_packets(&og) != 0) {
  390. last_granulepos = ogg_page_granulepos(&og);
  391. }
  392. last_segments -= og.header[26];
  393. int writtenPageBytes = writeOggPage(&og, _fileOs);
  394. if (writtenPageBytes != og.header_len + og.body_len) {
  395. LOGE("Error: failed writing data to output stream");
  396. return 0;
  397. }
  398. bytes_written += writtenPageBytes;
  399. pages_out++;
  400. }
  401. op.packet = _packet;
  402. op.bytes = nbBytes;
  403. op.b_o_s = 0;
  404. op.granulepos = enc_granulepos;
  405. if (op.e_o_s) {
  406. op.granulepos = ((total_samples * 48000 + rate - 1) / rate) + header.preskip;
  407. }
  408. op.packetno = 2 + _packetId;
  409. ogg_stream_packetin(&os, &op);
  410. last_segments += size_segments;
  411. 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)) {
  412. if (ogg_page_packets(&og) != 0) {
  413. last_granulepos = ogg_page_granulepos(&og);
  414. }
  415. last_segments -= og.header[26];
  416. int writtenPageBytes = writeOggPage(&og, _fileOs);
  417. if (writtenPageBytes != og.header_len + og.body_len) {
  418. LOGE("Error: failed writing data to output stream");
  419. return 0;
  420. }
  421. bytes_written += writtenPageBytes;
  422. pages_out++;
  423. }
  424. return 1;
  425. }
  426. JNIEXPORT jint Java_org_telegram_messenger_MediaController_startRecord(JNIEnv *env, jclass class, jstring path, jint sampleRate) {
  427. const char *pathStr = (*env)->GetStringUTFChars(env, path, 0);
  428. int32_t result = initRecorder(pathStr, sampleRate);
  429. if (pathStr != 0) {
  430. (*env)->ReleaseStringUTFChars(env, path, pathStr);
  431. }
  432. return result;
  433. }
  434. JNIEXPORT jint Java_org_telegram_messenger_MediaController_writeFrame(JNIEnv *env, jclass class, jobject frame, jint len) {
  435. jbyte *frameBytes = (*env)->GetDirectBufferAddress(env, frame);
  436. return writeFrame((uint8_t *) frameBytes, (uint32_t) len);
  437. }
  438. JNIEXPORT void Java_org_telegram_messenger_MediaController_stopRecord(JNIEnv *env, jclass class) {
  439. cleanupRecorder();
  440. }
  441. JNIEXPORT jint Java_org_telegram_messenger_MediaController_isOpusFile(JNIEnv *env, jclass class, jstring path) {
  442. const char *pathStr = (*env)->GetStringUTFChars(env, path, 0);
  443. int32_t result = 0;
  444. int32_t error = OPUS_OK;
  445. OggOpusFile *file = op_test_file(pathStr, &error);
  446. if (file != NULL) {
  447. error = op_test_open(file);
  448. op_free(file);
  449. result = error == OPUS_OK;
  450. }
  451. if (pathStr != 0) {
  452. (*env)->ReleaseStringUTFChars(env, path, pathStr);
  453. }
  454. return result;
  455. }
  456. static inline void set_bits(uint8_t *bytes, int32_t bitOffset, int32_t value) {
  457. bytes += bitOffset / 8;
  458. bitOffset %= 8;
  459. *((int32_t *) bytes) |= (value << bitOffset);
  460. }
  461. JNIEXPORT jbyteArray Java_org_telegram_messenger_MediaController_getWaveform2(JNIEnv *env, jclass class, jshortArray array, jint length) {
  462. jshort *sampleBuffer = (*env)->GetShortArrayElements(env, array, 0);
  463. const int32_t resultSamples = 100;
  464. uint16_t *samples = malloc(100 * 2);
  465. uint64_t sampleIndex = 0;
  466. uint16_t peakSample = 0;
  467. int32_t sampleRate = (int32_t) MAX(1, length / resultSamples);
  468. int32_t index = 0;
  469. for (int32_t i = 0; i < length; i++) {
  470. uint16_t sample = (uint16_t) abs(sampleBuffer[i]);
  471. if (sample > peakSample) {
  472. peakSample = sample;
  473. }
  474. if (sampleIndex++ % sampleRate == 0) {
  475. if (index < resultSamples) {
  476. samples[index++] = peakSample;
  477. }
  478. peakSample = 0;
  479. }
  480. }
  481. int64_t sumSamples = 0;
  482. for (int32_t i = 0; i < resultSamples; i++) {
  483. sumSamples += samples[i];
  484. }
  485. uint16_t peak = (uint16_t) (sumSamples * 1.8f / resultSamples);
  486. if (peak < 2500) {
  487. peak = 2500;
  488. }
  489. for (int32_t i = 0; i < resultSamples; i++) {
  490. uint16_t sample = (uint16_t) ((int64_t) samples[i]);
  491. if (sample > peak) {
  492. samples[i] = peak;
  493. }
  494. }
  495. (*env)->ReleaseShortArrayElements(env, array, sampleBuffer, 0);
  496. uint32_t bitstreamLength = resultSamples * 5 / 8 + 1;
  497. jbyteArray *result = (*env)->NewByteArray(env, bitstreamLength);
  498. if (result) {
  499. uint8_t *bytes = malloc(bitstreamLength + 4);
  500. memset(bytes, 0, bitstreamLength + 4);
  501. for (int32_t i = 0; i < resultSamples; i++) {
  502. int32_t value = MIN(31, abs((int32_t) samples[i]) * 31 / peak);
  503. set_bits(bytes, i * 5, value & 31);
  504. }
  505. (*env)->SetByteArrayRegion(env, result, 0, bitstreamLength, (jbyte *) bytes);
  506. }
  507. free(samples);
  508. return result;
  509. }
  510. int16_t *sampleBuffer = NULL;
  511. JNIEXPORT jbyteArray Java_org_telegram_messenger_MediaController_getWaveform(JNIEnv *env, jclass class, jstring path) {
  512. const char *pathStr = (*env)->GetStringUTFChars(env, path, 0);
  513. jbyteArray result = 0;
  514. int error = OPUS_OK;
  515. OggOpusFile *opusFile = op_open_file(pathStr, &error);
  516. if (opusFile != NULL && error == OPUS_OK) {
  517. int64_t totalSamples = op_pcm_total(opusFile, -1);
  518. const uint32_t resultSamples = 100;
  519. int32_t sampleRate = MAX(1, (int32_t) (totalSamples / resultSamples));
  520. uint16_t *samples = malloc(100 * 2);
  521. size_t bufferSize = 1024 * 128;
  522. if (sampleBuffer == NULL) {
  523. sampleBuffer = malloc(bufferSize);
  524. }
  525. uint64_t sampleIndex = 0;
  526. uint16_t peakSample = 0;
  527. int32_t index = 0;
  528. while (1) {
  529. int readSamples = op_read(opusFile, sampleBuffer, bufferSize / 2, NULL);
  530. for (int32_t i = 0; i < readSamples; i++) {
  531. uint16_t sample = (uint16_t) abs(sampleBuffer[i]);
  532. if (sample > peakSample) {
  533. peakSample = sample;
  534. }
  535. if (sampleIndex++ % sampleRate == 0) {
  536. if (index < resultSamples) {
  537. samples[index++] = peakSample;
  538. }
  539. peakSample = 0;
  540. }
  541. }
  542. if (readSamples == 0) {
  543. break;
  544. }
  545. }
  546. int64_t sumSamples = 0;
  547. for (int32_t i = 0; i < resultSamples; i++) {
  548. sumSamples += samples[i];
  549. }
  550. uint16_t peak = (uint16_t) (sumSamples * 1.8f / resultSamples);
  551. if (peak < 2500) {
  552. peak = 2500;
  553. }
  554. for (int32_t i = 0; i < resultSamples; i++) {
  555. uint16_t sample = (uint16_t) ((int64_t) samples[i]);
  556. if (sample > peak) {
  557. samples[i] = peak;
  558. }
  559. }
  560. //free(sampleBuffer);
  561. op_free(opusFile);
  562. uint32_t bitstreamLength = (resultSamples * 5) / 8 + 1;
  563. result = (*env)->NewByteArray(env, bitstreamLength);
  564. if (result) {
  565. uint8_t *bytes = malloc(bitstreamLength + 4);
  566. memset(bytes, 0, bitstreamLength + 4);
  567. for (int32_t i = 0; i < resultSamples; i++) {
  568. int32_t value = MIN(31, abs((int32_t) samples[i]) * 31 / peak);
  569. set_bits(bytes, i * 5, value & 31);
  570. }
  571. (*env)->SetByteArrayRegion(env, result, 0, bitstreamLength, (jbyte *) bytes);
  572. }
  573. free(samples);
  574. }
  575. if (pathStr != 0) {
  576. (*env)->ReleaseStringUTFChars(env, path, pathStr);
  577. }
  578. return result;
  579. }