1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448
|
/*
* MOC - music on console
* Copyright (C) 2005, 2006 Damian Pietras <daper@daper.net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Based on FFplay Copyright (c) 2003 Fabrice Bellard
*
*/
/*
* "The main problem is that external projects who want to
* support both FFmpeg and LibAV are just fucked, and this
* only because LibAV doesn't care a second about their users."
*
* -- http://blog.pkh.me/p/13-the-ffmpeg-libav-situation.html
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <strings.h>
#include <assert.h>
#include <stdint.h>
#include <errno.h>
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavutil/mathematics.h>
#if HAVE_LIBAVUTIL_CHANNEL_LAYOUT_H
# include <libavutil/channel_layout.h>
#else
# include <libavutil/audioconvert.h>
#endif
/* FFmpeg also likes common names, without that, our common.h and log.h
* would not be included. */
#undef COMMON_H
#undef LOG_H
#define DEBUG
#define STRERROR_FN ffmpeg_strerror
#include "common.h"
#include "audio.h"
#include "decoder.h"
#include "log.h"
#include "files.h"
#include "lists.h"
#ifndef AV_CODEC_CAP_DELAY
# define AV_CODEC_CAP_DELAY CODEC_CAP_DELAY
# define AV_CODEC_CAP_EXPERIMENTAL CODEC_CAP_EXPERIMENTAL
# define AV_CODEC_CAP_TRUNCATED CODEC_CAP_TRUNCATED
#endif
#ifndef AV_CODEC_FLAG_TRUNCATED
# define AV_CODEC_FLAG_TRUNCATED CODEC_FLAG_TRUNCATED
#endif
/* Set SEEK_IN_DECODER to 1 if you'd prefer seeking to be delay until
* the next time ffmpeg_decode() is called. This will provide seeking
* in formats for which FFmpeg falsely reports seek errors, but could
* result erroneous current time values. */
#define SEEK_IN_DECODER 0
struct ffmpeg_data
{
AVFormatContext *ic;
AVIOContext *pb;
AVStream *stream;
AVCodecContext *enc;
const AVCodec *codec;
char *remain_buf;
int remain_buf_len;
bool delay; /* FFmpeg may buffer samples */
bool eof; /* end of file seen */
bool eos; /* end of sound seen */
bool okay; /* was this stream successfully opened? */
char *filename;
struct io_stream *iostream;
struct decoder_error error;
long fmt;
int sample_width;
int bitrate; /* in bits per second */
int avg_bitrate; /* in bits per second */
#if SEEK_IN_DECODER
bool seek_req; /* seek requested */
int seek_sec; /* second to which to seek */
#endif
bool seek_broken; /* FFmpeg seeking is broken */
bool timing_broken; /* FFmpeg trashes duration and bit_rate */
#if SEEK_IN_DECODER && defined(DEBUG)
pthread_t thread_id;
#endif
};
struct extn_list {
const char *extn;
const char *format;
};
static lists_t_strs *supported_extns = NULL;
static void ffmpeg_log_repeats (char *msg LOGIT_ONLY)
{
#ifndef NDEBUG
static int msg_count = 0;
static char *prev_msg = NULL;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
/* We need to gate the decoder and precaching threads. */
LOCK (mutex);
if (prev_msg && (!msg || strcmp (msg, prev_msg))) {
if (msg_count > 1)
logit ("FFmpeg said: Last message repeated %d times", msg_count);
free (prev_msg);
prev_msg = NULL;
msg_count = 0;
}
if (prev_msg && msg) {
free (msg);
msg = NULL;
msg_count += 1;
}
if (!prev_msg && msg) {
int count, ix;
lists_t_strs *lines;
lines = lists_strs_new (4);
count = lists_strs_split (lines, msg, "\n");
for (ix = 0; ix < count; ix += 1)
logit ("FFmpeg said: %s", lists_strs_at (lines, ix));
lists_strs_free (lines);
prev_msg = msg;
msg_count = 1;
}
UNLOCK (mutex);
#endif
}
#ifndef NDEBUG
static void ffmpeg_log_cb (void *unused ATTR_UNUSED, int level,
const char *fmt, va_list vl)
{
int len;
char *msg;
assert (fmt);
if (level > av_log_get_level ())
return;
msg = format_msg_va (fmt, vl);
#if defined(HAVE_FFMPEG) && LIBAVFORMAT_VERSION_INT >= AV_VERSION_INT(56,33,101)
/* Drop this message because it is issued repeatedly and is pointless. */
const char skipping[] = "Skipping 0 bytes of junk";
if (!strncmp (skipping, msg, sizeof (skipping) - 1)) {
free (msg);
return;
}
#endif
len = strlen (msg);
for (len = strlen (msg); len > 0 && msg[len - 1] == '\n'; len -= 1)
msg[len - 1] = 0x00;
ffmpeg_log_repeats (msg);
}
#endif
/* FFmpeg-provided error code to description function wrapper. */
static inline char *ffmpeg_strerror (int errnum)
{
char *result;
ffmpeg_log_repeats (NULL);
result = xmalloc (256);
av_strerror (errnum, result, 256);
result[255] = 0;
return result;
}
/* Find the first audio stream and return its index, or nb_streams if
* none found. */
static unsigned int find_first_audio (AVFormatContext *ic)
{
unsigned int result;
assert (ic);
for (result = 0; result < ic->nb_streams; result += 1) {
enum AVMediaType codec_type;
#ifdef HAVE_STRUCT_AVSTREAM_CODECPAR
codec_type = ic->streams[result]->codecpar->codec_type;
#else
codec_type = ic->streams[result]->codec->codec_type;
#endif
if (codec_type == AVMEDIA_TYPE_AUDIO)
break;
}
return result;
}
static void load_audio_extns (lists_t_strs *list)
{
int ix;
/* When adding an entry to this list, tests need to be performed to
* determine whether or not FFmpeg/LibAV handles durations and seeking
* correctly. If not, then the appropriate additions should be made
* in is_timing_broken() and is_seek_broken(). */
const struct extn_list audio_extns[] = {
{"aac", "aac"},
{"ac3", "ac3"},
{"ape", "ape"},
{"au", "au"},
{"ay", "libgme"},
{"dff", "dsf"},
{"dsf", "dsf"},
{"dts", "dts"},
{"eac3", "eac3"},
{"fla", "flac"},
{"flac", "flac"},
{"gbs", "libgme"},
{"gym", "libgme"},
{"hes", "libgme"},
{"kss", "libgme"},
{"mka", "matroska"},
{"mp2", "mpeg"},
{"mp3", "mp3"},
{"mpc", "mpc"},
{"mpc8", "mpc8"},
{"m4a", "m4a"},
{"nsf", "libgme"},
{"nsfe", "libgme"},
{"ra", "rm"},
{"sap", "libgme"},
{"spc", "libgme"},
{"tta", "tta"},
{"vgm", "libgme"},
{"vgz", "libgme"},
{"vqf", "vqf"},
{"wav", "wav"},
{"w64", "w64"},
{"wma", "asf"},
{"wv", "wv"},
{NULL, NULL}
};
for (ix = 0; audio_extns[ix].extn; ix += 1) {
if (av_find_input_format (audio_extns[ix].format))
lists_strs_append (list, audio_extns[ix].extn);
}
if (av_find_input_format ("ogg")) {
lists_strs_append (list, "ogg");
if (avcodec_find_decoder (AV_CODEC_ID_VORBIS))
lists_strs_append (list, "oga");
if (avcodec_find_decoder (AV_CODEC_ID_OPUS))
lists_strs_append (list, "opus");
if (avcodec_find_decoder (AV_CODEC_ID_THEORA))
lists_strs_append (list, "ogv");
}
/* In theory, FFmpeg supports Speex if built with libspeex enabled.
* In practice, it breaks badly. */
#if 0
if (avcodec_find_decoder (AV_CODEC_ID_SPEEX))
lists_strs_append (list, "spx");
#endif
}
static void load_video_extns (lists_t_strs *list)
{
int ix;
const struct extn_list video_extns[] = {
{"avi", "avi"},
{"flv", "flv"},
{"mkv", "matroska"},
{"mp4", "mp4"},
{"rec", "mpegts"},
{"vob", "mpeg"},
{"webm", "matroska"},
{NULL, NULL}
};
for (ix = 0; video_extns[ix].extn; ix += 1) {
if (av_find_input_format (video_extns[ix].format))
lists_strs_append (list, video_extns[ix].extn);
}
}
/* Handle FFmpeg's locking requirements. */
#if HAVE_LIBAV || LIBAVCODEC_VERSION_INT < AV_VERSION_INT(58,9,100)
static int locking_cb (void **mutex, enum AVLockOp op)
{
int result;
switch (op) {
case AV_LOCK_CREATE:
*mutex = xmalloc (sizeof (pthread_mutex_t));
result = pthread_mutex_init (*mutex, NULL);
break;
case AV_LOCK_OBTAIN:
result = pthread_mutex_lock (*mutex);
break;
case AV_LOCK_RELEASE:
result = pthread_mutex_unlock (*mutex);
break;
case AV_LOCK_DESTROY:
result = pthread_mutex_destroy (*mutex);
free (*mutex);
*mutex = NULL;
break;
default:
/* We could return -1 here, but examination of the FFmpeg
* code shows that return code testing is erratic, so we'll
* take charge and complain loudly if FFmpeg/LibAV's API
* changes. This way we don't end up chasing phantoms. */
fatal ("Unexpected FFmpeg lock request received: %d", op);
}
return result;
}
#endif
/* Here we attempt to determine if FFmpeg/LibAV has trashed the 'duration'
* and 'bit_rate' fields in AVFormatContext for large files. Determining
* whether or not they are likely to be valid is imprecise and will vary
* depending (at least) on:
*
* - The file's size,
* - The file's codec,
* - The number and size of tags,
* - The version of FFmpeg/LibAV, and
* - Whether it's FFmpeg or LibAV.
*
* This function represents a best guess.
*/
static bool is_timing_broken (AVFormatContext *ic)
{
if (ic->duration < 0 || ic->bit_rate < 0)
return true;
/* If and when FFmpeg uses the right field for its calculation this
* should be self-correcting. */
if (ic->duration < AV_TIME_BASE && !strcmp (ic->iformat->name, "libgme"))
return true;
/* AAC timing is inaccurate. */
if (!strcmp (ic->iformat->name, "aac"))
return true;
/* Formats less than 4 GiB should be okay, except those excluded above. */
if (avio_size (ic->pb) < UINT32_MAX)
return false;
/* WAV files are limited to 4 GiB but that doesn't stop some encoders. */
if (!strcmp (ic->iformat->name, "wav"))
return true;
if (!strcmp (ic->iformat->name, "au"))
return true;
return false;
}
static void ffmpeg_init ()
{
#ifndef NDEBUG
# ifdef DEBUG
av_log_set_level (AV_LOG_INFO);
# else
av_log_set_level (AV_LOG_ERROR);
# endif
av_log_set_callback (ffmpeg_log_cb);
#endif
#if HAVE_LIBAV || LIBAVCODEC_VERSION_INT < AV_VERSION_INT(58,10,100)
avcodec_register_all ();
av_register_all ();
#endif
supported_extns = lists_strs_new (16);
load_audio_extns (supported_extns);
load_video_extns (supported_extns);
#if HAVE_LIBAV || LIBAVCODEC_VERSION_INT < AV_VERSION_INT(58,9,100)
int rc = av_lockmgr_register (locking_cb);
if (rc < 0) {
char buf[128];
av_strerror (rc, buf, sizeof (buf));
fatal ("Lock manager initialisation failed: %s", buf);
}
#endif
}
static void ffmpeg_destroy ()
{
#if HAVE_LIBAV || LIBAVCODEC_VERSION_INT < AV_VERSION_INT(58,9,100)
av_lockmgr_register (NULL);
#endif
av_log_set_level (AV_LOG_QUIET);
ffmpeg_log_repeats (NULL);
lists_strs_free (supported_extns);
}
/* Fill info structure with data from ffmpeg comments. */
static void ffmpeg_info (const char *file_name,
struct file_tags *info,
const int tags_sel)
{
int err;
AVFormatContext *ic = NULL;
AVDictionaryEntry *entry;
AVDictionary *md;
err = avformat_open_input (&ic, file_name, NULL, NULL);
if (err < 0) {
log_errno ("avformat_open_input() failed", err);
return;
}
err = avformat_find_stream_info (ic, NULL);
if (err < 0) {
log_errno ("avformat_find_stream_info() failed", err);
goto end;
}
if (!is_timing_broken (ic) && tags_sel & TAGS_TIME) {
info->time = -1;
if (ic->duration != (int64_t)AV_NOPTS_VALUE && ic->duration >= 0)
info->time = ic->duration / AV_TIME_BASE;
}
if (!(tags_sel & TAGS_COMMENTS))
goto end;
md = ic->metadata;
if (md == NULL) {
unsigned int audio_ix;
audio_ix = find_first_audio (ic);
if (audio_ix < ic->nb_streams)
md = ic->streams[audio_ix]->metadata;
}
if (md == NULL) {
debug ("no metadata found");
goto end;
}
entry = av_dict_get (md, "track", NULL, 0);
if (entry && entry->value && entry->value[0])
info->track = atoi (entry->value);
entry = av_dict_get (md, "title", NULL, 0);
if (entry && entry->value && entry->value[0])
info->title = xstrdup (entry->value);
entry = av_dict_get (md, "artist", NULL, 0);
if (entry && entry->value && entry->value[0])
info->artist = xstrdup (entry->value);
entry = av_dict_get (md, "album", NULL, 0);
if (entry && entry->value && entry->value[0])
info->album = xstrdup (entry->value);
end:
avformat_close_input (&ic);
ffmpeg_log_repeats (NULL);
}
static long fmt_from_sample_fmt (struct ffmpeg_data *data)
{
long result;
switch (data->enc->sample_fmt) {
case AV_SAMPLE_FMT_U8:
case AV_SAMPLE_FMT_U8P:
result = SFMT_U8;
break;
case AV_SAMPLE_FMT_S16:
case AV_SAMPLE_FMT_S16P:
result = SFMT_S16;
break;
case AV_SAMPLE_FMT_S32:
case AV_SAMPLE_FMT_S32P:
result = SFMT_S32;
break;
case AV_SAMPLE_FMT_FLT:
case AV_SAMPLE_FMT_FLTP:
result = SFMT_FLOAT;
break;
default:
result = 0;
}
return result;
}
/* Try to figure out if seeking is broken for this format.
* The aim here is to try and ensure that seeking either works
* properly or (because of FFmpeg breakages) is disabled. */
static bool is_seek_broken (struct ffmpeg_data *data)
{
#if 0
/* FFmpeg's alternate strategy for formats which don't
* support seeking natively seems to be... unreliable. */
if (!data->ic->iformat->read_seek) {
debug ("Seek broken by AVInputFormat.read_seek");
return true;
}
#endif
/* How much do we trust this? */
if (!(data->ic->pb->seekable & AVIO_SEEKABLE_NORMAL)) {
debug ("Seek broken by AVIOContext.seekable");
return true;
}
#if !SEEK_IN_DECODER
/* FLV (.flv): av_seek_frame always returns an error (even on success).
* Seeking from the decoder works for false errors (but
* probably not for real ones) because the player doesn't
* get to see them. */
# ifdef HAVE_FFMPEG
if (avcodec_version () < AV_VERSION_INT(55,8,100))
# else
if (avcodec_version () < AV_VERSION_INT(55,57,1))
# endif
{
if (!strcmp (data->ic->iformat->name, "flv"))
return true;
}
#endif
return false;
}
/* Downmix multi-channel audios to stereo. */
static void set_downmixing (struct ffmpeg_data *data)
{
if ((data->enc->ch_layout.nb_channels) <= 2)
return;
av_channel_layout_from_mask(&data->enc->ch_layout, AV_CH_LAYOUT_STEREO);
}
static int ffmpeg_io_read_cb (void *s, uint8_t *buf, int count)
{
int len;
if (!buf || count <= 0)
return AVERROR(EINVAL);
len = io_read ((struct io_stream *)s, buf, (size_t)count);
if (len == 0)
len = AVERROR_EOF;
else if (len < 0)
len = AVERROR(EIO);
return len;
}
static int64_t ffmpeg_io_seek_cb (void *s, int64_t offset, int whence)
{
int w;
int64_t result = -1;
/* Warning: Do not blindly accept the avio.h comments for AVSEEK_FORCE
* and AVSEEK_SIZE; they are incorrect for later FFmpeg/LibAV
* versions. */
w = whence & ~AVSEEK_FORCE;
switch (w) {
case SEEK_SET:
case SEEK_CUR:
case SEEK_END:
result = io_seek ((struct io_stream *)s, offset, w);
break;
case AVSEEK_SIZE:
result = io_file_size ((struct io_stream *)s);
break;
}
return result;
}
static struct ffmpeg_data *ffmpeg_make_data (void)
{
struct ffmpeg_data *data;
data = (struct ffmpeg_data *)xmalloc (sizeof (struct ffmpeg_data));
data->ic = NULL;
data->pb = NULL;
data->stream = NULL;
data->enc = NULL;
data->codec = NULL;
data->remain_buf = NULL;
data->remain_buf_len = 0;
data->delay = false;
data->eof = false;
data->eos = false;
data->okay = false;
data->filename = NULL;
data->iostream = NULL;
decoder_error_init (&data->error);
data->fmt = 0;
data->sample_width = 0;
data->bitrate = 0;
data->avg_bitrate = 0;
#if SEEK_IN_DECODER
data->seek_req = false;
data->seek_sec = 0;
#endif
data->seek_broken = false;
data->timing_broken = false;
#if SEEK_IN_DECODER && defined(DEBUG)
data->thread_id = 0;
#endif
return data;
}
static void *ffmpeg_open_internal (struct ffmpeg_data *data)
{
int err;
const char *extn = NULL;
unsigned int audio_ix;
data->ic = avformat_alloc_context ();
if (!data->ic)
fatal ("Can't allocate format context!");
data->ic->pb = avio_alloc_context (NULL, 0, 0, data->iostream,
ffmpeg_io_read_cb, NULL,
ffmpeg_io_seek_cb);
if (!data->ic->pb)
fatal ("Can't allocate avio context!");
/* Save AVIO context pointer so we can workaround an FFmpeg
* memory leak later in ffmpeg_close(). */
data->pb = data->ic->pb;
err = avformat_open_input (&data->ic, NULL, NULL, NULL);
if (err < 0) {
char *buf = ffmpeg_strerror (err);
decoder_error (&data->error, ERROR_FATAL, 0,
"Can't open audio: %s", buf);
free (buf);
return data;
}
/* When FFmpeg and LibAV misidentify a file's codec (and they do)
* then hopefully this will save MOC from wanton destruction. */
if (data->filename) {
extn = ext_pos (data->filename);
if (extn && !strcasecmp (extn, "wav")
&& strcmp (data->ic->iformat->name, "wav")) {
decoder_error (&data->error, ERROR_FATAL, 0,
"Format possibly misidentified "
"as '%s' by FFmpeg/LibAV",
data->ic->iformat->name);
goto end;
}
}
err = avformat_find_stream_info (data->ic, NULL);
if (err < 0) {
/* Depending on the particular FFmpeg/LibAV version in use, this
* may misreport experimental codecs. Given we don't know the
* codec at this time, we will have to live with it. */
char *buf = ffmpeg_strerror (err);
decoder_error (&data->error, ERROR_FATAL, 0,
"Could not find codec parameters: %s", buf);
free (buf);
goto end;
}
audio_ix = find_first_audio (data->ic);
if (audio_ix == data->ic->nb_streams) {
decoder_error (&data->error, ERROR_FATAL, 0, "No audio in source");
goto end;
}
data->stream = data->ic->streams[audio_ix];
data->enc = avcodec_alloc_context3 (NULL);
if (!data->enc) {
decoder_error (&data->error, ERROR_FATAL, 0,
"Failed to allocate codec context");
goto end;
}
#ifdef HAVE_STRUCT_AVSTREAM_CODECPAR
err = avcodec_parameters_to_context (data->enc, data->stream->codecpar);
if (err < 0) {
decoder_error (&data->error, ERROR_FATAL, 0,
"Failed to copy codec parameters");
goto end;
}
#else
err = avcodec_copy_context (data->enc, data->stream->codec);
if (err < 0) {
decoder_error (&data->error, ERROR_FATAL, 0,
"Failed to copy codec context");
goto end;
}
#endif
data->codec = avcodec_find_decoder (data->enc->codec_id);
if (!data->codec) {
decoder_error (&data->error, ERROR_FATAL, 0, "No codec for this audio");
goto end;
}
if (data->filename) {
const char *fn;
fn = strrchr (data->filename, '/');
fn = fn ? fn + 1 : data->filename;
debug ("FFmpeg thinks '%s' is format(codec) '%s(%s)'",
fn, data->ic->iformat->name, data->codec->name);
}
else
debug ("FFmpeg thinks stream is format(codec) '%s(%s)'",
data->ic->iformat->name, data->codec->name);
/* This may or may not work depending on the particular version of
* FFmpeg/LibAV in use. For some versions this will be caught in
* *_find_stream_info() above and misreported as an unfound codec
* parameters error. */
if (data->codec->capabilities & AV_CODEC_CAP_EXPERIMENTAL) {
decoder_error (&data->error, ERROR_FATAL, 0,
"The codec is experimental and may damage MOC: %s",
data->codec->name);
goto end;
}
set_downmixing (data);
if (avcodec_open2 (data->enc, data->codec, NULL) < 0)
{
decoder_error (&data->error, ERROR_FATAL, 0, "No codec for this audio");
goto end;
}
data->fmt = fmt_from_sample_fmt (data);
if (data->fmt == 0) {
decoder_error (&data->error, ERROR_FATAL, 0,
"Cannot get sample size from unknown sample format: %s",
av_get_sample_fmt_name (data->enc->sample_fmt));
goto end;
}
data->sample_width = sfmt_Bps (data->fmt);
if (data->codec->capabilities & AV_CODEC_CAP_DELAY)
data->delay = true;
data->seek_broken = is_seek_broken (data);
data->timing_broken = is_timing_broken (data->ic);
if (data->timing_broken && extn && !strcasecmp (extn, "wav")) {
ffmpeg_log_repeats (NULL);
decoder_error (&data->error, ERROR_FATAL, 0,
"Broken WAV file; use W64!");
goto end;
}
data->okay = true;
if (!data->timing_broken && data->ic->duration >= AV_TIME_BASE)
data->avg_bitrate = (int) (avio_size (data->ic->pb) /
(data->ic->duration / AV_TIME_BASE) * 8);
if (!data->timing_broken && data->ic->bit_rate > 0)
data->bitrate = data->ic->bit_rate;
return data;
end:
#ifdef HAVE_AVCODEC_FREE_CONTEXT
avcodec_free_context (&data->enc);
#else
avcodec_close (data->enc);
av_freep (&data->enc);
#endif
avformat_close_input (&data->ic);
ffmpeg_log_repeats (NULL);
return data;
}
static void *ffmpeg_open (const char *file)
{
struct ffmpeg_data *data;
data = ffmpeg_make_data ();
data->filename = xstrdup (file);
data->iostream = io_open (file, 1);
if (!io_ok (data->iostream)) {
decoder_error (&data->error, ERROR_FATAL, 0,
"Can't open file: %s", io_strerror (data->iostream));
return data;
}
return ffmpeg_open_internal (data);
}
static void *ffmpeg_open_stream (struct io_stream *stream)
{
struct ffmpeg_data *data;
data = ffmpeg_make_data ();
data->iostream = stream;
return ffmpeg_open_internal (data);
}
static int ffmpeg_can_decode (struct io_stream *stream)
{
int res;
AVProbeData probe_data;
const AVInputFormat *fmt;
char buf[8096 + AVPROBE_PADDING_SIZE] = {0};
res = io_peek (stream, buf, sizeof (buf));
if (res < 0) {
error ("Stream error: %s", io_strerror (stream));
return 0;
}
probe_data.filename = NULL;
probe_data.buf = (unsigned char*)buf;
probe_data.buf_size = sizeof (buf) - AVPROBE_PADDING_SIZE;
#ifdef HAVE_STRUCT_AVPROBEDATA_MIME_TYPE
probe_data.mime_type = NULL;
#endif
fmt = av_probe_input_format (&probe_data, 1);
return fmt != NULL;
}
static void put_in_remain_buf (struct ffmpeg_data *data, const char *buf,
const int len)
{
debug ("Remain: %dB", len);
data->remain_buf_len = len;
data->remain_buf = (char *)xmalloc (len);
memcpy (data->remain_buf, buf, len);
}
static void add_to_remain_buf (struct ffmpeg_data *data, const char *buf,
const int len)
{
debug ("Adding %dB to remain_buf", len);
data->remain_buf = (char *)xrealloc (data->remain_buf,
data->remain_buf_len + len);
memcpy (data->remain_buf + data->remain_buf_len, buf, len);
data->remain_buf_len += len;
debug ("remain_buf is %dB long", data->remain_buf_len);
}
/* Free the remainder buffer. */
static void free_remain_buf (struct ffmpeg_data *data)
{
free (data->remain_buf);
data->remain_buf = NULL;
data->remain_buf_len = 0;
}
/* Satisfy the request from previously decoded samples. */
static int take_from_remain_buf (struct ffmpeg_data *data, char *buf, int buf_len)
{
int to_copy = MIN (buf_len, data->remain_buf_len);
debug ("Copying %d bytes from the remain buf", to_copy);
memcpy (buf, data->remain_buf, to_copy);
if (to_copy < data->remain_buf_len) {
memmove (data->remain_buf, data->remain_buf + to_copy,
data->remain_buf_len - to_copy);
data->remain_buf_len -= to_copy;
}
else {
debug ("Remain buf is now empty");
free_remain_buf (data);
}
return to_copy;
}
/* Copy samples to output or remain buffer. */
static int copy_or_buffer (struct ffmpeg_data *data, char *in, int in_len,
char *out, int out_len)
{
if (in_len == 0)
return 0;
if (in_len <= out_len) {
memcpy (out, in, in_len);
return in_len;
}
if (out_len == 0) {
add_to_remain_buf (data, in, in_len);
return 0;
}
memcpy (out, in, out_len);
put_in_remain_buf (data, in + out_len, in_len - out_len);
return out_len;
}
/* Create a new packet ('cause FFmpeg doesn't provide one). */
static inline AVPacket *new_packet (struct ffmpeg_data *data)
{
AVPacket *pkt;
assert (data->stream);
#if HAVE_AV_PACKET_FNS
pkt = av_packet_alloc ();
#else
pkt = (AVPacket *)av_malloc (sizeof (AVPacket));
if (!pkt)
fatal ("av_malloc() failed to allocate memory");
av_init_packet (pkt);
pkt->data = NULL;
pkt->size = 0;
#endif
pkt->stream_index = data->stream->index;
return pkt;
}
static inline void free_packet (AVPacket *pkt)
{
#if HAVE_AV_PACKET_FNS
av_packet_free (&pkt);
#else
av_free_packet (pkt);
av_free (pkt);
#endif
}
/* Read a packet from the file or empty packet if flushing delayed
* samples. */
static AVPacket *get_packet (struct ffmpeg_data *data)
{
int rc;
AVPacket *pkt;
assert (data);
assert (!data->eos);
pkt = new_packet (data);
if (data->eof)
return pkt;
rc = av_read_frame (data->ic, pkt);
if (rc >= 0) {
debug ("Got %dB packet", pkt->size);
return pkt;
}
free_packet (pkt);
/* FFmpeg has (at least) two ways of indicating EOF. (Awesome!) */
if (rc == AVERROR_EOF)
data->eof = true;
if (data->ic->pb && data->ic->pb->eof_reached)
data->eof = true;
if (!data->eof && rc < 0) {
char *buf = ffmpeg_strerror (rc);
decoder_error (&data->error, ERROR_FATAL, 0,
"Error in the stream: %s", buf);
free (buf);
return NULL;
}
if (data->delay)
return new_packet (data);
data->eos = true;
return NULL;
}
#ifndef HAVE_AVCODEC_RECEIVE_FRAME
/* Decode samples from packet data using avcodec_decode_audio4(). */
# define decode_audio avcodec_decode_audio4
#endif
#ifdef HAVE_AVCODEC_RECEIVE_FRAME
/* Decode audio using FFmpeg's send/receive encoding and decoding API. */
static int decode_audio (AVCodecContext *ctx, AVFrame *frame,
int *got_frame_ptr, const AVPacket *pkt)
{
int rc, result = 0;
*got_frame_ptr = 0;
rc = avcodec_send_packet (ctx, pkt);
switch (rc) {
case 0:
break;
case AVERROR(EAGAIN):
debug ("avcodec_send_packet(): AVERROR(EAGAIN)");
break;
case AVERROR_EOF:
if (pkt->data)
debug ("avcodec_send_packet(): AVERROR_EOF");
break;
case AVERROR(EINVAL):
logit ("avcodec_send_packet(): AVERROR(EINVAL)");
result = rc;
break;
case AVERROR(ENOMEM):
logit ("avcodec_send_packet(): AVERROR(ENOMEM)");
result = rc;
break;
default:
log_errno ("avcodec_send_packet()", rc);
result = rc;
}
if (result == 0) {
result = pkt->size;
rc = avcodec_receive_frame (ctx, frame);
switch (rc) {
case 0:
*got_frame_ptr = 1;
break;
case AVERROR(EAGAIN):
debug ("avcodec_receive_frame(): AVERROR(EAGAIN)");
break;
case AVERROR_EOF:
debug ("avcodec_receive_frame(): AVERROR_EOF");
avcodec_flush_buffers (ctx);
break;
case AVERROR(EINVAL):
logit ("avcodec_receive_frame(): AVERROR(EINVAL)");
result = rc;
break;
default:
log_errno ("avcodec_receive_frame()", rc);
result = rc;
}
}
return result;
}
#endif
/* Decode samples from packet data. */
static int decode_packet (struct ffmpeg_data *data, AVPacket *pkt,
char *buf, int buf_len)
{
int filled = 0;
char *packed;
AVFrame *frame;
#ifdef HAVE_AV_FRAME_FNS
frame = av_frame_alloc ();
#else
frame = avcodec_alloc_frame ();
#endif
do {
int len, got_frame, is_planar, packed_size, copied;
len = decode_audio (data->enc, frame, &got_frame, pkt);
if (len < 0) {
/* skip frame */
decoder_error (&data->error, ERROR_STREAM, 0,
"Error in the stream!");
break;
}
debug ("Decoded %dB", len);
pkt->data += len;
pkt->size -= len;
if (!got_frame) {
data->eos = data->eof && (pkt->size == 0);
continue;
}
if (frame->nb_samples == 0)
continue;
is_planar = av_sample_fmt_is_planar (data->enc->sample_fmt);
packed = (char *)frame->extended_data[0];
packed_size = frame->nb_samples * data->sample_width
* data->enc->ch_layout.nb_channels;
if (is_planar && data->enc->ch_layout.nb_channels > 1) {
int sample, ch;
packed = xmalloc (packed_size);
for (sample = 0; sample < frame->nb_samples; sample += 1) {
for (ch = 0; ch < data->enc->ch_layout.nb_channels; ch += 1)
memcpy (packed + (sample * data->enc->ch_layout.nb_channels + ch)
* data->sample_width,
(char *)frame->extended_data[ch] + sample * data->sample_width,
data->sample_width);
}
}
copied = copy_or_buffer (data, packed, packed_size, buf, buf_len);
buf += copied;
filled += copied;
buf_len -= copied;
debug ("Copying %dB (%dB filled)", packed_size, filled);
if (packed != (char *)frame->extended_data[0])
free (packed);
} while (pkt->size > 0);
#ifdef HAVE_AV_FRAME_FNS
av_frame_free (&frame);
#else
avcodec_free_frame (&frame);
#endif
return filled;
}
#if SEEK_IN_DECODER
static bool seek_in_stream (struct ffmpeg_data *data)
#else
static bool seek_in_stream (struct ffmpeg_data *data, int sec)
#endif
{
int rc;
int64_t seek_ts;
#if SEEK_IN_DECODER
int sec = data->seek_sec;
#ifdef DEBUG
assert (pthread_equal (data->thread_id, pthread_self ()));
#endif
#endif
/* FFmpeg can't seek if the file has already reached EOF. */
if (data->eof)
return false;
seek_ts = av_rescale (sec, data->stream->time_base.den,
data->stream->time_base.num);
if (data->stream->start_time != (int64_t)AV_NOPTS_VALUE) {
if (seek_ts > INT64_MAX - MAX(0, data->stream->start_time)) {
logit ("Seek value too large");
return false;
}
seek_ts += data->stream->start_time;
}
rc = av_seek_frame (data->ic, data->stream->index, seek_ts,
AVSEEK_FLAG_BACKWARD);
if (rc < 0) {
log_errno ("Seek error", rc);
return false;
}
avcodec_flush_buffers (data->enc);
return true;
}
static inline int compute_bitrate (struct sound_params *sound_params,
int bytes_used, int bytes_produced,
int bitrate)
{
int64_t bytes_per_frame, bytes_per_second, seconds;
bytes_per_frame = sfmt_Bps (sound_params->fmt) * sound_params->channels;
bytes_per_second = bytes_per_frame * (int64_t)sound_params->rate;
seconds = (int64_t)bytes_produced / bytes_per_second;
if (seconds > 0)
bitrate = (int)((int64_t)bytes_used * 8 / seconds);
return bitrate;
}
static int ffmpeg_decode (void *prv_data, char *buf, int buf_len,
struct sound_params *sound_params)
{
struct ffmpeg_data *data = (struct ffmpeg_data *)prv_data;
int bytes_used = 0, bytes_produced = 0;
decoder_error_clear (&data->error);
if (data->eos)
return 0;
/* FFmpeg claims to always return native endian. */
sound_params->channels = data->enc->ch_layout.nb_channels;
sound_params->rate = data->enc->sample_rate;
sound_params->fmt = data->fmt | SFMT_NE;
#if SEEK_IN_DECODER
if (data->seek_req) {
data->seek_req = false;
if (seek_in_stream (data))
free_remain_buf (data);
}
#endif
if (data->remain_buf)
return take_from_remain_buf (data, buf, buf_len);
do {
uint8_t *saved_pkt_data_ptr;
AVPacket *pkt;
pkt = get_packet (data);
if (!pkt)
break;
if (pkt->stream_index != data->stream->index) {
free_packet (pkt);
continue;
}
#ifdef AV_PKT_FLAG_CORRUPT
if (pkt->flags & AV_PKT_FLAG_CORRUPT) {
ffmpeg_log_repeats (NULL);
debug ("Dropped corrupt packet.");
free_packet (pkt);
continue;
}
#endif
saved_pkt_data_ptr = pkt->data;
bytes_used += pkt->size;
bytes_produced = decode_packet (data, pkt, buf, buf_len);
buf += bytes_produced;
buf_len -= bytes_produced;
/* FFmpeg will segfault if the data pointer is not restored. */
pkt->data = saved_pkt_data_ptr;
free_packet (pkt);
} while (!bytes_produced && !data->eos);
if (!data->timing_broken)
data->bitrate = compute_bitrate (sound_params, bytes_used,
bytes_produced + data->remain_buf_len,
data->bitrate);
return bytes_produced;
}
static int ffmpeg_seek (void *prv_data, int sec)
{
struct ffmpeg_data *data = (struct ffmpeg_data *)prv_data;
assert (sec >= 0);
if (data->seek_broken)
return -1;
#if SEEK_IN_DECODER
data->seek_sec = sec;
data->seek_req = true;
#ifdef DEBUG
data->thread_id = pthread_self ();
#endif
#else
if (!seek_in_stream (data, sec))
return -1;
free_remain_buf (data);
#endif
return sec;
}
static void ffmpeg_close (void *prv_data)
{
struct ffmpeg_data *data = (struct ffmpeg_data *)prv_data;
/* We need to delve into the AVIOContext struct to free the
* buffer FFmpeg leaked if avformat_open_input() failed. Do
* not be tempted to call avio_close() here; it will segfault. */
if (data->pb) {
av_freep (&data->pb->buffer);
av_freep (&data->pb);
}
if (data->okay) {
#ifdef HAVE_AVCODEC_FREE_CONTEXT
avcodec_free_context (&data->enc);
#else
avcodec_close (data->enc);
av_freep (&data->enc);
#endif
avformat_close_input (&data->ic);
free_remain_buf (data);
}
ffmpeg_log_repeats (NULL);
if (data->iostream) {
io_close (data->iostream);
data->iostream = NULL;
}
decoder_error_clear (&data->error);
free (data->filename);
free (data);
}
static struct io_stream *ffmpeg_get_iostream (void *prv_data)
{
struct ffmpeg_data *data;
assert (prv_data);
data = (struct ffmpeg_data *)prv_data;
return data->iostream;
}
static int ffmpeg_get_bitrate (void *prv_data)
{
struct ffmpeg_data *data = (struct ffmpeg_data *)prv_data;
return data->timing_broken ? -1 : data->bitrate / 1000;
}
static int ffmpeg_get_avg_bitrate (void *prv_data)
{
struct ffmpeg_data *data = (struct ffmpeg_data *)prv_data;
return data->timing_broken ? -1 : data->avg_bitrate / 1000;
}
static int ffmpeg_get_duration (void *prv_data)
{
struct ffmpeg_data *data = (struct ffmpeg_data *)prv_data;
if (data->timing_broken)
return -1;
if (!data->stream)
return -1;
if (data->stream->duration == (int64_t)AV_NOPTS_VALUE)
return -1;
if (data->stream->duration < 0)
return -1;
return data->stream->duration * data->stream->time_base.num
/ data->stream->time_base.den;
}
static int ffmpeg_our_format_ext (const char *ext)
{
return (lists_strs_exists (supported_extns, ext)) ? 1 : 0;
}
static int ffmpeg_our_format_mime (const char *mime_type)
{
const AVOutputFormat *fmt;
fmt = av_guess_format (NULL, NULL, mime_type);
return fmt ? 1 : 0;
}
static void ffmpeg_get_error (void *prv_data, struct decoder_error *error)
{
struct ffmpeg_data *data = (struct ffmpeg_data *)prv_data;
decoder_error_copy (error, &data->error);
}
static struct decoder ffmpeg_decoder = {
DECODER_API_VERSION,
ffmpeg_init,
ffmpeg_destroy,
ffmpeg_open,
ffmpeg_open_stream,
ffmpeg_can_decode,
ffmpeg_close,
ffmpeg_decode,
ffmpeg_seek,
ffmpeg_info,
ffmpeg_get_bitrate,
ffmpeg_get_duration,
ffmpeg_get_error,
ffmpeg_our_format_ext,
ffmpeg_our_format_mime,
NULL,
NULL,
ffmpeg_get_iostream,
ffmpeg_get_avg_bitrate
};
struct decoder *plugin_init ()
{
return &ffmpeg_decoder;
}
|