alffmpeg.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  1. /*
  2. * FFmpeg Decoder Helpers
  3. *
  4. * Copyright (c) 2011 by Chris Robinson <[email protected]>
  5. *
  6. * Permission is hereby granted, free of charge, to any person obtaining a copy
  7. * of this software and associated documentation files (the "Software"), to deal
  8. * in the Software without restriction, including without limitation the rights
  9. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. * copies of the Software, and to permit persons to whom the Software is
  11. * furnished to do so, subject to the following conditions:
  12. *
  13. * The above copyright notice and this permission notice shall be included in
  14. * all copies or substantial portions of the Software.
  15. *
  16. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. * THE SOFTWARE.
  23. */
  24. /* This file contains routines for helping to decode audio using libavformat
  25. * and libavcodec (ffmpeg). There's very little OpenAL-specific code here. */
  26. #include <string.h>
  27. #include <stdlib.h>
  28. #include <stdio.h>
  29. #include <signal.h>
  30. #include <assert.h>
  31. #include "AL/al.h"
  32. #include "AL/alc.h"
  33. #include "AL/alext.h"
  34. #include "alhelpers.h"
  35. #include "alffmpeg.h"
  36. static size_t NextPowerOf2(size_t value)
  37. {
  38. size_t powerOf2 = 1;
  39. if(value)
  40. {
  41. value--;
  42. while(value)
  43. {
  44. value >>= 1;
  45. powerOf2 <<= 1;
  46. }
  47. }
  48. return powerOf2;
  49. }
  50. struct MemData {
  51. char *buffer;
  52. size_t length;
  53. size_t pos;
  54. };
  55. static int MemData_read(void *opaque, uint8_t *buf, int buf_size)
  56. {
  57. struct MemData *membuf = (struct MemData*)opaque;
  58. int rem = membuf->length - membuf->pos;
  59. if(rem > buf_size)
  60. rem = buf_size;
  61. memcpy(buf, &membuf->buffer[membuf->pos], rem);
  62. membuf->pos += rem;
  63. return rem;
  64. }
  65. static int MemData_write(void *opaque, uint8_t *buf, int buf_size)
  66. {
  67. struct MemData *membuf = (struct MemData*)opaque;
  68. int rem = membuf->length - membuf->pos;
  69. if(rem > buf_size)
  70. rem = buf_size;
  71. memcpy(&membuf->buffer[membuf->pos], buf, rem);
  72. membuf->pos += rem;
  73. return rem;
  74. }
  75. static int64_t MemData_seek(void *opaque, int64_t offset, int whence)
  76. {
  77. struct MemData *membuf = (struct MemData*)opaque;
  78. whence &= ~AVSEEK_FORCE;
  79. switch(whence)
  80. {
  81. case SEEK_SET:
  82. if(offset < 0 || offset > membuf->length)
  83. return -1;
  84. membuf->pos = offset;
  85. break;
  86. case SEEK_CUR:
  87. if((offset >= 0 && offset > membuf->length-membuf->pos) ||
  88. (offset < 0 && offset < -membuf->pos))
  89. return -1;
  90. membuf->pos += offset;
  91. break;
  92. case SEEK_END:
  93. if(offset > 0 || offset < -membuf->length)
  94. return -1;
  95. membuf->pos = membuf->length + offset;
  96. break;
  97. case AVSEEK_SIZE:
  98. return membuf->length;
  99. default:
  100. return -1;
  101. }
  102. return membuf->pos;
  103. }
  104. struct PacketList {
  105. AVPacket pkt;
  106. struct PacketList *next;
  107. };
  108. struct MyStream {
  109. AVCodecContext *CodecCtx;
  110. int StreamIdx;
  111. struct PacketList *Packets;
  112. char *DecodedData;
  113. size_t DecodedDataSize;
  114. FilePtr parent;
  115. };
  116. struct MyFile {
  117. AVFormatContext *FmtCtx;
  118. StreamPtr *Streams;
  119. size_t StreamsSize;
  120. struct MemData membuf;
  121. };
  122. static int done_init = 0;
  123. FilePtr openAVFile(const char *fname)
  124. {
  125. FilePtr file;
  126. /* We need to make sure ffmpeg is initialized. Optionally silence warning
  127. * output from the lib */
  128. if(!done_init) {av_register_all();
  129. av_log_set_level(AV_LOG_ERROR);
  130. done_init = 1;}
  131. file = (FilePtr)calloc(1, sizeof(*file));
  132. if(file && avformat_open_input(&file->FmtCtx, fname, NULL, NULL) == 0)
  133. {
  134. /* After opening, we must search for the stream information because not
  135. * all formats will have it in stream headers */
  136. if(avformat_find_stream_info(file->FmtCtx, NULL) >= 0)
  137. return file;
  138. av_close_input_file(file->FmtCtx);
  139. }
  140. free(file);
  141. return NULL;
  142. }
  143. FilePtr openAVData(const char *name, char *buffer, size_t buffer_len)
  144. {
  145. FilePtr file;
  146. if(!done_init) {av_register_all();
  147. av_log_set_level(AV_LOG_ERROR);
  148. done_init = 1;}
  149. if(!name)
  150. name = "";
  151. file = (FilePtr)calloc(1, sizeof(*file));
  152. if(file && (file->FmtCtx=avformat_alloc_context()) != NULL)
  153. {
  154. file->membuf.buffer = buffer;
  155. file->membuf.length = buffer_len;
  156. file->membuf.pos = 0;
  157. file->FmtCtx->pb = avio_alloc_context(NULL, 0, 0, &file->membuf,
  158. MemData_read, MemData_write,
  159. MemData_seek);
  160. if(file->FmtCtx->pb && avformat_open_input(&file->FmtCtx, name, NULL, NULL) == 0)
  161. {
  162. if(avformat_find_stream_info(file->FmtCtx, NULL) >= 0)
  163. return file;
  164. }
  165. av_close_input_file(file->FmtCtx);
  166. }
  167. free(file);
  168. return NULL;
  169. }
  170. FilePtr openAVCustom(const char *name, void *user_data,
  171. int (*read_packet)(void *user_data, uint8_t *buf, int buf_size),
  172. int (*write_packet)(void *user_data, uint8_t *buf, int buf_size),
  173. int64_t (*seek)(void *user_data, int64_t offset, int whence))
  174. {
  175. FilePtr file;
  176. if(!done_init) {av_register_all();
  177. av_log_set_level(AV_LOG_ERROR);
  178. done_init = 1;}
  179. if(!name)
  180. name = "";
  181. file = (FilePtr)calloc(1, sizeof(*file));
  182. if(file && (file->FmtCtx=avformat_alloc_context()) != NULL)
  183. {
  184. file->FmtCtx->pb = avio_alloc_context(NULL, 0, 0, user_data,
  185. read_packet, write_packet, seek);
  186. if(file->FmtCtx->pb && avformat_open_input(&file->FmtCtx, name, NULL, NULL) == 0)
  187. {
  188. if(avformat_find_stream_info(file->FmtCtx, NULL) >= 0)
  189. return file;
  190. }
  191. av_close_input_file(file->FmtCtx);
  192. }
  193. free(file);
  194. return NULL;
  195. }
  196. void closeAVFile(FilePtr file)
  197. {
  198. size_t i;
  199. if(!file) return;
  200. for(i = 0;i < file->StreamsSize;i++)
  201. {
  202. StreamPtr stream = file->Streams[i];
  203. while(stream->Packets)
  204. {
  205. struct PacketList *self;
  206. self = stream->Packets;
  207. stream->Packets = self->next;
  208. av_free_packet(&self->pkt);
  209. av_free(self);
  210. }
  211. avcodec_close(stream->CodecCtx);
  212. av_free(stream->DecodedData);
  213. free(stream);
  214. }
  215. free(file->Streams);
  216. av_close_input_file(file->FmtCtx);
  217. free(file);
  218. }
  219. int getAVFileInfo(FilePtr file, int *numaudiostreams)
  220. {
  221. unsigned int i;
  222. int audiocount = 0;
  223. if(!file) return 1;
  224. for(i = 0;i < file->FmtCtx->nb_streams;i++)
  225. {
  226. if(file->FmtCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO)
  227. audiocount++;
  228. }
  229. *numaudiostreams = audiocount;
  230. return 0;
  231. }
  232. StreamPtr getAVAudioStream(FilePtr file, int streamnum)
  233. {
  234. unsigned int i;
  235. if(!file) return NULL;
  236. for(i = 0;i < file->FmtCtx->nb_streams;i++)
  237. {
  238. if(file->FmtCtx->streams[i]->codec->codec_type != AVMEDIA_TYPE_AUDIO)
  239. continue;
  240. if(streamnum == 0)
  241. {
  242. StreamPtr stream;
  243. AVCodec *codec;
  244. void *temp;
  245. size_t j;
  246. /* Found the requested stream. Check if a handle to this stream
  247. * already exists and return it if it does */
  248. for(j = 0;j < file->StreamsSize;j++)
  249. {
  250. if(file->Streams[j]->StreamIdx == (int)i)
  251. return file->Streams[j];
  252. }
  253. /* Doesn't yet exist. Now allocate a new stream object and fill in
  254. * its info */
  255. stream = (StreamPtr)calloc(1, sizeof(*stream));
  256. if(!stream) return NULL;
  257. stream->parent = file;
  258. stream->CodecCtx = file->FmtCtx->streams[i]->codec;
  259. stream->StreamIdx = i;
  260. /* Try to find the codec for the given codec ID, and open it */
  261. codec = avcodec_find_decoder(stream->CodecCtx->codec_id);
  262. if(!codec || avcodec_open(stream->CodecCtx, codec) < 0)
  263. {
  264. free(stream);
  265. return NULL;
  266. }
  267. /* Allocate space for the decoded data to be stored in before it
  268. * gets passed to the app */
  269. stream->DecodedData = (char*)av_malloc(AVCODEC_MAX_AUDIO_FRAME_SIZE);
  270. if(!stream->DecodedData)
  271. {
  272. avcodec_close(stream->CodecCtx);
  273. free(stream);
  274. return NULL;
  275. }
  276. /* Append the new stream object to the stream list. The original
  277. * pointer will remain valid if realloc fails, so we need to use
  278. * another pointer to watch for errors and not leak memory */
  279. temp = realloc(file->Streams, (file->StreamsSize+1) *
  280. sizeof(*file->Streams));
  281. if(!temp)
  282. {
  283. avcodec_close(stream->CodecCtx);
  284. av_free(stream->DecodedData);
  285. free(stream);
  286. return NULL;
  287. }
  288. file->Streams = (StreamPtr*)temp;
  289. file->Streams[file->StreamsSize++] = stream;
  290. return stream;
  291. }
  292. streamnum--;
  293. }
  294. return NULL;
  295. }
  296. int getAVAudioInfo(StreamPtr stream, ALuint *rate, ALenum *channels, ALenum *type)
  297. {
  298. if(!stream || stream->CodecCtx->codec_type != AVMEDIA_TYPE_AUDIO)
  299. return 1;
  300. /* Get the sample type for OpenAL given the format detected by ffmpeg. */
  301. if(stream->CodecCtx->sample_fmt == AV_SAMPLE_FMT_U8)
  302. *type = AL_UNSIGNED_BYTE_SOFT;
  303. else if(stream->CodecCtx->sample_fmt == AV_SAMPLE_FMT_S16)
  304. *type = AL_SHORT_SOFT;
  305. else if(stream->CodecCtx->sample_fmt == AV_SAMPLE_FMT_S32)
  306. *type = AL_INT_SOFT;
  307. else if(stream->CodecCtx->sample_fmt == AV_SAMPLE_FMT_FLT)
  308. *type = AL_FLOAT_SOFT;
  309. else if(stream->CodecCtx->sample_fmt == AV_SAMPLE_FMT_DBL)
  310. *type = AL_DOUBLE_SOFT;
  311. else
  312. {
  313. fprintf(stderr, "Unsupported ffmpeg sample format: %s\n",
  314. av_get_sample_fmt_name(stream->CodecCtx->sample_fmt));
  315. return 1;
  316. }
  317. /* Get the OpenAL channel configuration using the channel layout detected
  318. * by ffmpeg. NOTE: some file types may not specify a channel layout. In
  319. * that case, one must be guessed based on the channel count. */
  320. if(stream->CodecCtx->channel_layout == AV_CH_LAYOUT_MONO)
  321. *channels = AL_MONO_SOFT;
  322. else if(stream->CodecCtx->channel_layout == AV_CH_LAYOUT_STEREO)
  323. *channels = AL_STEREO_SOFT;
  324. else if(stream->CodecCtx->channel_layout == AV_CH_LAYOUT_QUAD)
  325. *channels = AL_QUAD_SOFT;
  326. else if(stream->CodecCtx->channel_layout == AV_CH_LAYOUT_5POINT1_BACK)
  327. *channels = AL_5POINT1_SOFT;
  328. else if(stream->CodecCtx->channel_layout == AV_CH_LAYOUT_7POINT1)
  329. *channels = AL_7POINT1_SOFT;
  330. else if(stream->CodecCtx->channel_layout == 0)
  331. {
  332. /* Unknown channel layout. Try to guess. */
  333. if(stream->CodecCtx->channels == 1)
  334. *channels = AL_MONO_SOFT;
  335. else if(stream->CodecCtx->channels == 2)
  336. *channels = AL_STEREO_SOFT;
  337. else
  338. {
  339. fprintf(stderr, "Unsupported ffmpeg raw channel count: %d\n",
  340. stream->CodecCtx->channels);
  341. return 1;
  342. }
  343. }
  344. else
  345. {
  346. char str[1024];
  347. av_get_channel_layout_string(str, sizeof(str), stream->CodecCtx->channels,
  348. stream->CodecCtx->channel_layout);
  349. fprintf(stderr, "Unsupported ffmpeg channel layout: %s\n", str);
  350. return 1;
  351. }
  352. *rate = stream->CodecCtx->sample_rate;
  353. return 0;
  354. }
  355. /* Used by getAV*Data to search for more compressed data, and buffer it in the
  356. * correct stream. It won't buffer data for streams that the app doesn't have a
  357. * handle for. */
  358. static int getNextPacket(FilePtr file, int streamidx)
  359. {
  360. struct PacketList *packet;
  361. packet = (struct PacketList*)av_malloc(sizeof(*packet));
  362. packet->next = NULL;
  363. next_packet:
  364. while(av_read_frame(file->FmtCtx, &packet->pkt) >= 0)
  365. {
  366. StreamPtr *iter = file->Streams;
  367. StreamPtr *iter_end = iter + file->StreamsSize;
  368. /* Check each stream the user has a handle for, looking for the one
  369. * this packet belongs to */
  370. while(iter != iter_end)
  371. {
  372. if((*iter)->StreamIdx == packet->pkt.stream_index)
  373. {
  374. struct PacketList **last;
  375. last = &(*iter)->Packets;
  376. while(*last != NULL)
  377. last = &(*last)->next;
  378. *last = packet;
  379. if((*iter)->StreamIdx == streamidx)
  380. return 1;
  381. packet = (struct PacketList*)av_malloc(sizeof(*packet));
  382. packet->next = NULL;
  383. goto next_packet;
  384. }
  385. iter++;
  386. }
  387. /* Free the packet and look for another */
  388. av_free_packet(&packet->pkt);
  389. }
  390. av_free(packet);
  391. return 0;
  392. }
  393. void *getAVAudioData(StreamPtr stream, size_t *length)
  394. {
  395. int size;
  396. int len;
  397. if(length) *length = 0;
  398. if(!stream || stream->CodecCtx->codec_type != AVMEDIA_TYPE_AUDIO)
  399. return NULL;
  400. stream->DecodedDataSize = 0;
  401. next_packet:
  402. if(!stream->Packets && !getNextPacket(stream->parent, stream->StreamIdx))
  403. return NULL;
  404. /* Decode some data, and check for errors */
  405. size = AVCODEC_MAX_AUDIO_FRAME_SIZE;
  406. while((len=avcodec_decode_audio3(stream->CodecCtx,
  407. (int16_t*)stream->DecodedData, &size,
  408. &stream->Packets->pkt)) == 0)
  409. {
  410. struct PacketList *self;
  411. if(size > 0)
  412. break;
  413. /* Packet went unread and no data was given? Drop it and try the next,
  414. * I guess... */
  415. self = stream->Packets;
  416. stream->Packets = self->next;
  417. av_free_packet(&self->pkt);
  418. av_free(self);
  419. if(!stream->Packets)
  420. goto next_packet;
  421. size = AVCODEC_MAX_AUDIO_FRAME_SIZE;
  422. }
  423. if(len < 0)
  424. return NULL;
  425. if(len < stream->Packets->pkt.size)
  426. {
  427. /* Move the unread data to the front and clear the end bits */
  428. int remaining = stream->Packets->pkt.size - len;
  429. memmove(stream->Packets->pkt.data, &stream->Packets->pkt.data[len],
  430. remaining);
  431. memset(&stream->Packets->pkt.data[remaining], 0,
  432. stream->Packets->pkt.size - remaining);
  433. stream->Packets->pkt.size -= len;
  434. }
  435. else
  436. {
  437. struct PacketList *self;
  438. self = stream->Packets;
  439. stream->Packets = self->next;
  440. av_free_packet(&self->pkt);
  441. av_free(self);
  442. }
  443. if(size == 0)
  444. goto next_packet;
  445. /* Set the output buffer size */
  446. stream->DecodedDataSize = size;
  447. if(length) *length = stream->DecodedDataSize;
  448. return stream->DecodedData;
  449. }
  450. size_t readAVAudioData(StreamPtr stream, void *data, size_t length)
  451. {
  452. size_t dec = 0;
  453. if(!stream || stream->CodecCtx->codec_type != AVMEDIA_TYPE_AUDIO)
  454. return 0;
  455. while(dec < length)
  456. {
  457. /* If there's no decoded data, find some */
  458. if(stream->DecodedDataSize == 0)
  459. {
  460. if(getAVAudioData(stream, NULL) == NULL)
  461. break;
  462. }
  463. if(stream->DecodedDataSize > 0)
  464. {
  465. /* Get the amount of bytes remaining to be written, and clamp to
  466. * the amount of decoded data we have */
  467. size_t rem = length-dec;
  468. if(rem > stream->DecodedDataSize)
  469. rem = stream->DecodedDataSize;
  470. /* Copy the data to the app's buffer and increment */
  471. if(data != NULL)
  472. {
  473. memcpy(data, stream->DecodedData, rem);
  474. data = (char*)data + rem;
  475. }
  476. dec += rem;
  477. /* If there's any decoded data left, move it to the front of the
  478. * buffer for next time */
  479. if(rem < stream->DecodedDataSize)
  480. memmove(stream->DecodedData, &stream->DecodedData[rem],
  481. stream->DecodedDataSize - rem);
  482. stream->DecodedDataSize -= rem;
  483. }
  484. }
  485. /* Return the number of bytes we were able to get */
  486. return dec;
  487. }
  488. void *decodeAVAudioStream(StreamPtr stream, size_t *length)
  489. {
  490. char *outbuf = NULL;
  491. size_t buflen = 0;
  492. void *inbuf;
  493. size_t got;
  494. *length = 0;
  495. if(!stream || stream->CodecCtx->codec_type != AVMEDIA_TYPE_AUDIO)
  496. return NULL;
  497. while((inbuf=getAVAudioData(stream, &got)) != NULL && got > 0)
  498. {
  499. void *ptr;
  500. ptr = realloc(outbuf, NextPowerOf2(buflen+got));
  501. if(ptr == NULL)
  502. break;
  503. outbuf = (char*)ptr;
  504. memcpy(&outbuf[buflen], inbuf, got);
  505. buflen += got;
  506. }
  507. outbuf = (char*)realloc(outbuf, buflen);
  508. *length = buflen;
  509. return outbuf;
  510. }