00001
00002 #include <cassert>
00003 #include <unistd.h>
00004 #include <cmath>
00005 #include <stdint.h>
00006
00007
00008 #include <algorithm>
00009 #include <iostream>
00010 using namespace std;
00011
00012 #include <QTextCodec>
00013
00014
00015 #include "mythtvexp.h"
00016 #include "mythconfig.h"
00017 #include "avformatdecoder.h"
00018 #include "privatedecoder.h"
00019 #include "audiooutput.h"
00020 #include "audiooutpututil.h"
00021 #include "ringbuffer.h"
00022 #include "mythplayer.h"
00023 #include "remoteencoder.h"
00024 #include "programinfo.h"
00025 #include "mythcorecontext.h"
00026 #include "mythdbcon.h"
00027 #include "iso639.h"
00028 #include "mpegtables.h"
00029 #include "atscdescriptors.h"
00030 #include "dvbdescriptors.h"
00031 #include "cc608decoder.h"
00032 #include "cc708decoder.h"
00033 #include "teletextdecoder.h"
00034 #include "subtitlereader.h"
00035 #include "interactivetv.h"
00036 #include "videodisplayprofile.h"
00037 #include "mythuihelper.h"
00038 #include "DVD/dvdringbuffer.h"
00039 #include "Bluray/bdringbuffer.h"
00040
00041 #include "lcddevice.h"
00042
00043 #include "videoout_quartz.h"
00044
00045 #ifdef USING_VDPAU
00046 #include "videoout_vdpau.h"
00047 extern "C" {
00048 #include "libavcodec/vdpau.h"
00049 }
00050 #endif // USING_VDPAU
00051
00052 #ifdef USING_DXVA2
00053 #include "videoout_d3d.h"
00054 #endif
00055
00056 #ifdef USING_GLVAAPI
00057 #include "videoout_openglvaapi.h"
00058 #endif // USING_GLVAAPI
00059 #ifdef USING_VAAPI
00060 #include "vaapicontext.h"
00061 #endif
00062
00063 extern "C" {
00064 #include "libavutil/avutil.h"
00065 #include "libavutil/log.h"
00066 #include "libavcodec/avcodec.h"
00067 #include "libavcodec/ac3_parser.h"
00068 #include "libavcodec/mpegvideo.h"
00069 #include "libavformat/avformat.h"
00070 #include "libavformat/avio.h"
00071 #include "libavformat/internal.h"
00072 #include "libswscale/swscale.h"
00073 #include "ivtv_myth.h"
00074 }
00075
00076 #ifdef _MSC_VER
00077
00078 # ifdef AV_TIME_BASE_Q
00079 # undef AV_TIME_BASE_Q
00080 # endif
00081 #define AV_TIME_BASE_Q GetAVTimeBaseQ()
00082
00083 __inline AVRational GetAVTimeBaseQ()
00084 {
00085 AVRational av = {1, AV_TIME_BASE};
00086 return av;
00087 }
00088 #endif
00089
00090 #define LOC QString("AFD: ")
00091
00092 #define MAX_AC3_FRAME_SIZE 6144
00093
00094 static const float eps = 1E-5;
00095
00096 static const int max_video_queue_size = 220;
00097
00098 static int cc608_parity(uint8_t byte);
00099 static int cc608_good_parity(const int *parity_table, uint16_t data);
00100 static void cc608_build_parity_table(int *parity_table);
00101
00102 static bool silence_ffmpeg_logging = false;
00103
00104 static QSize get_video_dim(const AVCodecContext &ctx)
00105 {
00106 return QSize(ctx.width >> ctx.lowres, ctx.height >> ctx.lowres);
00107 }
00108 static float get_aspect(const AVCodecContext &ctx)
00109 {
00110 float aspect_ratio = 0.0f;
00111
00112 if (ctx.sample_aspect_ratio.num && ctx.height)
00113 {
00114 aspect_ratio = av_q2d(ctx.sample_aspect_ratio) * (float) ctx.width;
00115 aspect_ratio /= (float) ctx.height;
00116 }
00117
00118 if (aspect_ratio <= 0.0f || aspect_ratio > 6.0f)
00119 {
00120 if (ctx.height)
00121 aspect_ratio = (float)ctx.width / (float)ctx.height;
00122 else
00123 aspect_ratio = 4.0f / 3.0f;
00124 }
00125
00126 return aspect_ratio;
00127 }
00128
00129 int get_avf_buffer(struct AVCodecContext *c, AVFrame *pic);
00130 void release_avf_buffer(struct AVCodecContext *c, AVFrame *pic);
00131 int get_avf_buffer_vdpau(struct AVCodecContext *c, AVFrame *pic);
00132 void release_avf_buffer_vdpau(struct AVCodecContext *c, AVFrame *pic);
00133 void render_slice_vdpau(struct AVCodecContext *s, const AVFrame *src,
00134 int offset[4], int y, int type, int height);
00135 int get_avf_buffer_dxva2(struct AVCodecContext *c, AVFrame *pic);
00136 int get_avf_buffer_vaapi(struct AVCodecContext *c, AVFrame *pic);
00137
00138 static AVCodec *find_vdpau_decoder(AVCodec *c, enum CodecID id)
00139 {
00140 AVCodec *codec = c;
00141 while (codec)
00142 {
00143 if (codec->id == id && CODEC_IS_VDPAU(codec))
00144 return codec;
00145
00146 codec = codec->next;
00147 }
00148
00149 return c;
00150 }
00151
00152 static void myth_av_log(void *ptr, int level, const char* fmt, va_list vl)
00153 {
00154 if (silence_ffmpeg_logging)
00155 return;
00156
00157 if (VERBOSE_LEVEL_NONE)
00158 return;
00159
00160 static QString full_line("");
00161 static const int msg_len = 255;
00162 static QMutex string_lock;
00163 uint64_t verbose_mask = VB_GENERAL;
00164 LogLevel_t verbose_level = LOG_DEBUG;
00165
00166
00167 switch (level)
00168 {
00169 case AV_LOG_PANIC:
00170 verbose_level = LOG_EMERG;
00171 break;
00172 case AV_LOG_FATAL:
00173 verbose_level = LOG_CRIT;
00174 break;
00175 case AV_LOG_ERROR:
00176 verbose_level = LOG_ERR;
00177 verbose_mask |= VB_LIBAV;
00178 break;
00179 case AV_LOG_DEBUG:
00180 case AV_LOG_VERBOSE:
00181 case AV_LOG_INFO:
00182 verbose_level = LOG_DEBUG;
00183 verbose_mask |= VB_LIBAV;
00184 break;
00185 case AV_LOG_WARNING:
00186 verbose_mask |= VB_LIBAV;
00187 break;
00188 default:
00189 return;
00190 }
00191
00192 if (!VERBOSE_LEVEL_CHECK(verbose_mask, verbose_level))
00193 return;
00194
00195 string_lock.lock();
00196 if (full_line.isEmpty() && ptr) {
00197 AVClass* avc = *(AVClass**)ptr;
00198 full_line.sprintf("[%s @ %p] ", avc->item_name(ptr), avc);
00199 }
00200
00201 char str[msg_len+1];
00202 int bytes = vsnprintf(str, msg_len+1, fmt, vl);
00203
00204
00205 if (bytes > msg_len)
00206 {
00207 LOG(VB_GENERAL, LOG_WARNING,
00208 QString("Libav log output truncated %1 of %2 bytes written")
00209 .arg(msg_len).arg(bytes));
00210 str[msg_len-1] = '\n';
00211 }
00212
00213 full_line += QString(str);
00214 if (full_line.endsWith("\n"))
00215 {
00216 LOG(verbose_mask, verbose_level, full_line.trimmed());
00217 full_line.truncate(0);
00218 }
00219 string_lock.unlock();
00220 }
00221
00222 static int get_canonical_lang(const char *lang_cstr)
00223 {
00224 if (lang_cstr[0] == '\0' || lang_cstr[1] == '\0')
00225 {
00226 return iso639_str3_to_key("und");
00227 }
00228 else if (lang_cstr[2] == '\0')
00229 {
00230 QString tmp2 = lang_cstr;
00231 QString tmp3 = iso639_str2_to_str3(tmp2);
00232 int lang = iso639_str3_to_key(tmp3);
00233 return iso639_key_to_canonical_key(lang);
00234 }
00235 else
00236 {
00237 int lang = iso639_str3_to_key(lang_cstr);
00238 return iso639_key_to_canonical_key(lang);
00239 }
00240 }
00241
00242 void AvFormatDecoder::GetDecoders(render_opts &opts)
00243 {
00244 opts.decoders->append("ffmpeg");
00245 (*opts.equiv_decoders)["ffmpeg"].append("nuppel");
00246 (*opts.equiv_decoders)["ffmpeg"].append("dummy");
00247
00248 #ifdef USING_VDPAU
00249 opts.decoders->append("vdpau");
00250 (*opts.equiv_decoders)["vdpau"].append("dummy");
00251 #endif
00252 #ifdef USING_DXVA2
00253 opts.decoders->append("dxva2");
00254 (*opts.equiv_decoders)["dxva2"].append("dummy");
00255 #endif
00256
00257 #ifdef USING_VAAPI
00258 opts.decoders->append("vaapi");
00259 (*opts.equiv_decoders)["vaapi"].append("dummy");
00260 #endif
00261
00262 PrivateDecoder::GetDecoders(opts);
00263 }
00264
00265 AvFormatDecoder::AvFormatDecoder(MythPlayer *parent,
00266 const ProgramInfo &pginfo,
00267 PlayerFlags flags)
00268 : DecoderBase(parent, pginfo),
00269 private_dec(NULL),
00270 is_db_ignored(gCoreContext->IsDatabaseIgnored()),
00271 m_h264_parser(new H264Parser()),
00272 ic(NULL),
00273 frame_decoded(0), decoded_video_frame(NULL),
00274 avfRingBuffer(NULL), sws_ctx(NULL),
00275 directrendering(false),
00276 no_dts_hack(false), dorewind(false),
00277 gopset(false), seen_gop(false),
00278 seq_count(0),
00279 prevgoppos(0), gotVideoFrame(false),
00280 hasVideo(false), needDummyVideoFrames(false),
00281 skipaudio(false), allowedquit(false),
00282 start_code_state(0xffffffff),
00283 lastvpts(0), lastapts(0),
00284 lastccptsu(0),
00285 firstvpts(0), firstvptsinuse(false),
00286 faulty_pts(0), faulty_dts(0),
00287 last_pts_for_fault_detection(0),
00288 last_dts_for_fault_detection(0),
00289 pts_detected(false),
00290 reordered_pts_detected(false),
00291 pts_selected(true),
00292 force_dts_timestamps(false),
00293 playerFlags(flags),
00294 video_codec_id(kCodec_NONE),
00295 maxkeyframedist(-1),
00296
00297 ignore_scte(false),
00298 invert_scte_field(0),
00299 last_scte_field(0),
00300 ccd608(new CC608Decoder(parent->GetCC608Reader())),
00301 ccd708(new CC708Decoder(parent->GetCC708Reader())),
00302 ttd(new TeletextDecoder(parent->GetTeletextReader())),
00303
00304 itv(NULL),
00305
00306 disable_passthru(false),
00307 m_fps(0.0f),
00308 codec_is_mpeg(false)
00309 {
00310 memset(&readcontext, 0, sizeof(readcontext));
00311 memset(ccX08_in_pmt, 0, sizeof(ccX08_in_pmt));
00312 memset(ccX08_in_tracks, 0, sizeof(ccX08_in_tracks));
00313
00314 audioSamples = (uint8_t *)av_mallocz(AVCODEC_MAX_AUDIO_FRAME_SIZE *
00315 sizeof(int32_t));
00316 ccd608->SetIgnoreTimecode(true);
00317
00318 bool debug = VERBOSE_LEVEL_CHECK(VB_LIBAV, LOG_ANY);
00319 av_log_set_level((debug) ? AV_LOG_DEBUG : AV_LOG_ERROR);
00320 av_log_set_callback(myth_av_log);
00321
00322 audioIn.sample_size = -32;
00323 itv = m_parent->GetInteractiveTV();
00324
00325 cc608_build_parity_table(cc608_parity_table);
00326
00327 LOG(VB_PLAYBACK, LOG_DEBUG, LOC + QString("PlayerFlags: 0x%1")
00328 .arg(playerFlags, 0, 16));
00329 }
00330
00331 AvFormatDecoder::~AvFormatDecoder()
00332 {
00333 while (!storedPackets.isEmpty())
00334 {
00335 AVPacket *pkt = storedPackets.takeFirst();
00336 av_free_packet(pkt);
00337 delete pkt;
00338 }
00339
00340 CloseContext();
00341 delete ccd608;
00342 delete ccd708;
00343 delete ttd;
00344 delete private_dec;
00345 delete m_h264_parser;
00346
00347 sws_freeContext(sws_ctx);
00348
00349 av_free(audioSamples);
00350
00351 if (avfRingBuffer)
00352 delete avfRingBuffer;
00353
00354 if (LCD *lcd = LCD::Get())
00355 {
00356 lcd->setAudioFormatLEDs(AUDIO_AC3, false);
00357 lcd->setVideoFormatLEDs(VIDEO_MPG, false);
00358 lcd->setVariousLEDs(VARIOUS_HDTV, false);
00359 lcd->setVariousLEDs(VARIOUS_SPDIF, false);
00360 lcd->setSpeakerLEDs(SPEAKER_71, false);
00361 }
00362 }
00363
00364 void AvFormatDecoder::CloseCodecs()
00365 {
00366 if (ic)
00367 {
00368 for (uint i = 0; i < ic->nb_streams; i++)
00369 {
00370 QMutexLocker locker(avcodeclock);
00371 AVStream *st = ic->streams[i];
00372 if (st->codec->codec)
00373 avcodec_close(st->codec);
00374 }
00375 }
00376 }
00377
00378 void AvFormatDecoder::CloseContext()
00379 {
00380 if (ic)
00381 {
00382 CloseCodecs();
00383
00384 AVInputFormat *fmt = ic->iformat;
00385 ic->iformat->flags |= AVFMT_NOFILE;
00386
00387 av_free(ic->pb->buffer);
00388 av_free(ic->pb);
00389 avformat_close_input(&ic);
00390 ic = NULL;
00391 fmt->flags &= ~AVFMT_NOFILE;
00392 }
00393
00394 delete private_dec;
00395 private_dec = NULL;
00396 m_h264_parser->Reset();
00397 }
00398
00399 static int64_t lsb3full(int64_t lsb, int64_t base_ts, int lsb_bits)
00400 {
00401 int64_t mask = (lsb_bits < 64) ? (1LL<<lsb_bits)-1 : -1LL;
00402 return ((lsb - base_ts)&mask);
00403 }
00404
00405 int64_t AvFormatDecoder::NormalizeVideoTimecode(int64_t timecode)
00406 {
00407 int64_t start_pts = 0, pts;
00408
00409 AVStream *st = NULL;
00410 for (uint i = 0; i < ic->nb_streams; i++)
00411 {
00412 AVStream *st1 = ic->streams[i];
00413 if (st1 && st1->codec->codec_type == AVMEDIA_TYPE_VIDEO)
00414 {
00415 st = st1;
00416 break;
00417 }
00418 }
00419 if (!st)
00420 return false;
00421
00422 if (ic->start_time != (int64_t)AV_NOPTS_VALUE)
00423 start_pts = av_rescale(ic->start_time,
00424 st->time_base.den,
00425 AV_TIME_BASE * (int64_t)st->time_base.num);
00426
00427 pts = av_rescale(timecode / 1000.0,
00428 st->time_base.den,
00429 st->time_base.num);
00430
00431
00432 pts = lsb3full(pts, start_pts, st->pts_wrap_bits);
00433
00434 return (int64_t)(av_q2d(st->time_base) * pts * 1000);
00435 }
00436
00437 int64_t AvFormatDecoder::NormalizeVideoTimecode(AVStream *st,
00438 int64_t timecode)
00439 {
00440 int64_t start_pts = 0, pts;
00441
00442 if (ic->start_time != (int64_t)AV_NOPTS_VALUE)
00443 start_pts = av_rescale(ic->start_time,
00444 st->time_base.den,
00445 AV_TIME_BASE * (int64_t)st->time_base.num);
00446
00447 pts = av_rescale(timecode / 1000.0,
00448 st->time_base.den,
00449 st->time_base.num);
00450
00451
00452 pts = lsb3full(pts, start_pts, st->pts_wrap_bits);
00453
00454 return (int64_t)(av_q2d(st->time_base) * pts * 1000);
00455 }
00456
00457 int AvFormatDecoder::GetNumChapters()
00458 {
00459 if (ic->nb_chapters > 1)
00460 return ic->nb_chapters;
00461 return 0;
00462 }
00463
00464 void AvFormatDecoder::GetChapterTimes(QList<long long> ×)
00465 {
00466 int total = GetNumChapters();
00467 if (!total)
00468 return;
00469
00470 for (int i = 0; i < total; i++)
00471 {
00472 int num = ic->chapters[i]->time_base.num;
00473 int den = ic->chapters[i]->time_base.den;
00474 int64_t start = ic->chapters[i]->start;
00475 long double total_secs = (long double)start * (long double)num /
00476 (long double)den;
00477 times.push_back((long long)total_secs);
00478 }
00479 }
00480
00481 int AvFormatDecoder::GetCurrentChapter(long long framesPlayed)
00482 {
00483 if (!GetNumChapters())
00484 return 0;
00485
00486 for (int i = (ic->nb_chapters - 1); i > -1 ; i--)
00487 {
00488 int num = ic->chapters[i]->time_base.num;
00489 int den = ic->chapters[i]->time_base.den;
00490 int64_t start = ic->chapters[i]->start;
00491 long double total_secs = (long double)start * (long double)num /
00492 (long double)den;
00493 long long framenum = (long long)(total_secs * fps);
00494 if (framesPlayed >= framenum)
00495 {
00496 LOG(VB_PLAYBACK, LOG_INFO, LOC +
00497 QString("GetCurrentChapter(selected chapter %1 framenum %2)")
00498 .arg(i + 1).arg(framenum));
00499 return i + 1;
00500 }
00501 }
00502 return 0;
00503 }
00504
00505 long long AvFormatDecoder::GetChapter(int chapter)
00506 {
00507 if (chapter < 1 || chapter > GetNumChapters())
00508 return -1;
00509
00510 int num = ic->chapters[chapter - 1]->time_base.num;
00511 int den = ic->chapters[chapter - 1]->time_base.den;
00512 int64_t start = ic->chapters[chapter - 1]->start;
00513 long double total_secs = (long double)start * (long double)num /
00514 (long double)den;
00515 long long framenum = (long long)(total_secs * fps);
00516 LOG(VB_PLAYBACK, LOG_INFO, LOC + QString("GetChapter %1: framenum %2")
00517 .arg(chapter).arg(framenum));
00518 return framenum;
00519 }
00520
00521 bool AvFormatDecoder::DoRewind(long long desiredFrame, bool discardFrames)
00522 {
00523 LOG(VB_PLAYBACK, LOG_INFO, LOC + QString("DoRewind(%1, %2 discard frames)")
00524 .arg(desiredFrame).arg( discardFrames ? "do" : "don't" ));
00525
00526 if (recordingHasPositionMap || livetv)
00527 return DecoderBase::DoRewind(desiredFrame, discardFrames);
00528
00529 dorewind = true;
00530
00531
00532 return DoFastForward(desiredFrame, discardFrames);
00533 }
00534
00535 bool AvFormatDecoder::DoFastForward(long long desiredFrame, bool discardFrames)
00536 {
00537 LOG(VB_PLAYBACK, LOG_INFO, LOC +
00538 QString("DoFastForward(%1 (%2), %3 discard frames)")
00539 .arg(desiredFrame).arg(framesPlayed)
00540 .arg((discardFrames) ? "do" : "don't"));
00541
00542 if (recordingHasPositionMap || livetv)
00543 return DecoderBase::DoFastForward(desiredFrame, discardFrames);
00544
00545 bool oldrawstate = getrawframes;
00546 getrawframes = false;
00547
00548 AVStream *st = NULL;
00549 for (uint i = 0; i < ic->nb_streams; i++)
00550 {
00551 AVStream *st1 = ic->streams[i];
00552 if (st1 && st1->codec->codec_type == AVMEDIA_TYPE_VIDEO)
00553 {
00554 st = st1;
00555 break;
00556 }
00557 }
00558 if (!st)
00559 return false;
00560
00561 int seekDelta = desiredFrame - framesPlayed;
00562
00563
00564 if (seekDelta >= 0 && seekDelta < 2 && !dorewind && m_parent->GetPlaySpeed() == 0.0f)
00565 {
00566 SeekReset(framesPlayed, seekDelta, false, true);
00567 m_parent->SetFramesPlayed(framesPlayed + 1);
00568 return true;
00569 }
00570
00571 long long ts = 0;
00572 if (ic->start_time != (int64_t)AV_NOPTS_VALUE)
00573 ts = ic->start_time;
00574
00575
00576 long double seekts = desiredFrame * AV_TIME_BASE / fps;
00577 ts += (long long)seekts;
00578
00579
00580 bool exactseeks = !DecoderBase::GetSeekSnap();
00581
00582 int flags = (dorewind || exactseeks) ? AVSEEK_FLAG_BACKWARD : 0;
00583
00584 if (av_seek_frame(ic, -1, ts, flags) < 0)
00585 {
00586 LOG(VB_GENERAL, LOG_ERR, LOC +
00587 QString("av_seek_frame(ic, -1, %1, 0) -- error").arg(ts));
00588 return false;
00589 }
00590
00591 int normalframes = 0;
00592
00593 if (st->cur_dts != (int64_t)AV_NOPTS_VALUE)
00594 {
00595
00596 int64_t adj_cur_dts = st->cur_dts;
00597
00598 if (ic->start_time != (int64_t)AV_NOPTS_VALUE)
00599 {
00600 int64_t st1 = av_rescale(ic->start_time,
00601 st->time_base.den,
00602 AV_TIME_BASE * (int64_t)st->time_base.num);
00603 adj_cur_dts = lsb3full(adj_cur_dts, st1, st->pts_wrap_bits);
00604 }
00605
00606 int64_t adj_seek_dts = av_rescale(seekts,
00607 st->time_base.den,
00608 AV_TIME_BASE * (int64_t)st->time_base.num);
00609
00610 int64_t max_dts = (st->pts_wrap_bits < 64) ? (1LL<<st->pts_wrap_bits)-1 : -1LL;
00611
00612
00613
00614
00615 if (adj_seek_dts < max_dts / 64 && adj_cur_dts > max_dts / 2)
00616 adj_cur_dts = 0;
00617
00618 long long newts = av_rescale(adj_cur_dts,
00619 (int64_t)AV_TIME_BASE *
00620 (int64_t)st->time_base.num,
00621 st->time_base.den);
00622
00623 lastKey = (long long)((newts*(long double)fps)/AV_TIME_BASE);
00624 framesPlayed = lastKey;
00625 framesRead = lastKey;
00626
00627 normalframes = (exactseeks) ? desiredFrame - framesPlayed : 0;
00628 normalframes = max(normalframes, 0);
00629 no_dts_hack = false;
00630 }
00631 else
00632 {
00633 LOG(VB_GENERAL, LOG_INFO, LOC + "No DTS Seeking Hack!");
00634 no_dts_hack = true;
00635 framesPlayed = desiredFrame;
00636 framesRead = desiredFrame;
00637 normalframes = 0;
00638 }
00639
00640 SeekReset(lastKey, normalframes, true, discardFrames);
00641
00642 if (discardFrames)
00643 m_parent->SetFramesPlayed(framesPlayed + 1);
00644
00645 dorewind = false;
00646
00647 getrawframes = oldrawstate;
00648
00649 return true;
00650 }
00651
00652 void AvFormatDecoder::SeekReset(long long newKey, uint skipFrames,
00653 bool doflush, bool discardFrames)
00654 {
00655 if (ringBuffer->IsInDiscMenuOrStillFrame() || newKey == 0)
00656 return;
00657
00658 LOG(VB_PLAYBACK, LOG_INFO, LOC +
00659 QString("SeekReset(%1, %2, %3 flush, %4 discard)")
00660 .arg(newKey).arg(skipFrames)
00661 .arg((doflush) ? "do" : "don't")
00662 .arg((discardFrames) ? "do" : "don't"));
00663
00664 DecoderBase::SeekReset(newKey, skipFrames, doflush, discardFrames);
00665
00666 if (doflush)
00667 {
00668 lastapts = 0;
00669 lastvpts = 0;
00670 lastccptsu = 0;
00671 faulty_pts = faulty_dts = 0;
00672 last_pts_for_fault_detection = 0;
00673 last_dts_for_fault_detection = 0;
00674 pts_detected = false;
00675 reordered_pts_detected = false;
00676
00677 ff_read_frame_flush(ic);
00678
00679
00680
00681 if (recordingHasPositionMap || livetv)
00682 {
00683 ic->pb->pos = ringBuffer->GetReadPosition();
00684 ic->pb->buf_ptr = ic->pb->buffer;
00685 ic->pb->buf_end = ic->pb->buffer;
00686 ic->pb->eof_reached = 0;
00687 }
00688
00689
00690 LOG(VB_PLAYBACK, LOG_INFO, LOC + "SeekReset() flushing");
00691 for (uint i = 0; i < ic->nb_streams; i++)
00692 {
00693 AVCodecContext *enc = ic->streams[i]->codec;
00694 if (enc->codec)
00695 avcodec_flush_buffers(enc);
00696 }
00697 if (private_dec)
00698 private_dec->Reset();
00699 }
00700
00701
00702 if (discardFrames)
00703 m_parent->DiscardVideoFrames(doflush);
00704
00705 if (doflush)
00706 {
00707
00708 while (!storedPackets.isEmpty())
00709 {
00710 AVPacket *pkt = storedPackets.takeFirst();
00711 av_free_packet(pkt);
00712 delete pkt;
00713 }
00714
00715 prevgoppos = 0;
00716 gopset = false;
00717 if (!ringBuffer->IsDVD())
00718 {
00719 if (!no_dts_hack)
00720 {
00721 framesPlayed = lastKey;
00722 framesRead = lastKey;
00723 }
00724
00725 no_dts_hack = false;
00726 }
00727 }
00728
00729
00730 for (;skipFrames > 0 && !ateof; skipFrames--)
00731 {
00732 GetFrame(kDecodeVideo);
00733 if (decoded_video_frame)
00734 {
00735 m_parent->DiscardVideoFrame(decoded_video_frame);
00736 decoded_video_frame = NULL;
00737 }
00738 }
00739
00740 if (doflush)
00741 {
00742 firstvpts = 0;
00743 firstvptsinuse = true;
00744 }
00745 }
00746
00747 void AvFormatDecoder::SetEof(bool eof)
00748 {
00749 if (!eof && ic && ic->pb)
00750 {
00751 LOG(VB_GENERAL, LOG_NOTICE, LOC +
00752 QString("Resetting byte context eof (livetv %1 was eof %2)")
00753 .arg(livetv).arg(ic->pb->eof_reached));
00754 ic->pb->eof_reached = 0;
00755 }
00756 DecoderBase::SetEof(eof);
00757 }
00758
00759 void AvFormatDecoder::Reset(bool reset_video_data, bool seek_reset,
00760 bool reset_file)
00761 {
00762 LOG(VB_PLAYBACK, LOG_INFO, LOC +
00763 QString("Reset: Video %1, Seek %2, File %3")
00764 .arg(reset_video_data).arg(seek_reset).arg(reset_file));
00765
00766 if (seek_reset)
00767 SeekReset(0, 0, true, false);
00768
00769 DecoderBase::Reset(reset_video_data, false, reset_file);
00770
00771 if (reset_video_data)
00772 {
00773 seen_gop = false;
00774 seq_count = 0;
00775 }
00776 }
00777
00778 bool AvFormatDecoder::CanHandle(char testbuf[kDecoderProbeBufferSize],
00779 const QString &filename, int testbufsize)
00780 {
00781 {
00782 QMutexLocker locker(avcodeclock);
00783 av_register_all();
00784 }
00785
00786 AVProbeData probe;
00787
00788 QByteArray fname = filename.toAscii();
00789 probe.filename = fname.constData();
00790 probe.buf = (unsigned char *)testbuf;
00791 probe.buf_size = testbufsize;
00792
00793 int score = AVPROBE_SCORE_MAX/4;
00794
00795 if (testbufsize + AVPROBE_PADDING_SIZE > kDecoderProbeBufferSize)
00796 {
00797 probe.buf_size = kDecoderProbeBufferSize - AVPROBE_PADDING_SIZE;
00798 score = 0;
00799 }
00800 else if (testbufsize*2 >= kDecoderProbeBufferSize)
00801 {
00802 score--;
00803 }
00804
00805 if (av_probe_input_format2(&probe, true, &score))
00806 return true;
00807 return false;
00808 }
00809
00810 void AvFormatDecoder::InitByteContext(void)
00811 {
00812 int buf_size = ringBuffer->BestBufferSize();
00813 int streamed = ringBuffer->IsStreamed();
00814 LOG(VB_PLAYBACK, LOG_INFO, LOC + QString("Buffer size: %1, streamed %2")
00815 .arg(buf_size).arg(streamed));
00816
00817 readcontext.prot = &AVF_RingBuffer_Protocol;
00818 readcontext.flags = AVIO_FLAG_READ;
00819 readcontext.is_streamed = streamed;
00820 readcontext.max_packet_size = 0;
00821 readcontext.priv_data = avfRingBuffer;
00822 unsigned char* buffer = (unsigned char *)av_malloc(buf_size);
00823 ic->pb = avio_alloc_context(buffer, buf_size, 0,
00824 &readcontext,
00825 AVF_Read_Packet,
00826 AVF_Write_Packet,
00827 AVF_Seek_Packet);
00828
00829 ic->pb->seekable = !streamed;
00830 }
00831
00832 extern "C" void HandleStreamChange(void *data)
00833 {
00834 AvFormatDecoder *decoder =
00835 reinterpret_cast<AvFormatDecoder*>(data);
00836
00837 int cnt = decoder->ic->nb_streams;
00838
00839 LOG(VB_PLAYBACK, LOG_INFO, LOC +
00840 QString("streams_changed 0x%1 -- stream count %2")
00841 .arg((uint64_t)data,0,16).arg(cnt));
00842
00843 QMutexLocker locker(avcodeclock);
00844 decoder->SeekReset(0, 0, true, true);
00845 decoder->ScanStreams(false);
00846 }
00847
00848 extern "C" void HandleDVDStreamChange(void *data)
00849 {
00850 AvFormatDecoder *decoder =
00851 reinterpret_cast<AvFormatDecoder*>(data);
00852
00853 int cnt = decoder->ic->nb_streams;
00854
00855 LOG(VB_PLAYBACK, LOG_INFO, LOC +
00856 QString("streams_changed 0x%1 -- stream count %2")
00857 .arg((uint64_t)data,0,16).arg(cnt));
00858
00859 QMutexLocker locker(avcodeclock);
00860
00861 decoder->ScanStreams(true);
00862 }
00863
00864 extern "C" void HandleBDStreamChange(void *data)
00865 {
00866 AvFormatDecoder *decoder =
00867 reinterpret_cast<AvFormatDecoder*>(data);
00868
00869 LOG(VB_PLAYBACK, LOG_INFO, LOC + "resetting");
00870
00871 QMutexLocker locker(avcodeclock);
00872 decoder->Reset(true, false, false);
00873 decoder->CloseCodecs();
00874 decoder->FindStreamInfo();
00875 decoder->ScanStreams(false);
00876 }
00877
00878 int AvFormatDecoder::FindStreamInfo(void)
00879 {
00880 QMutexLocker lock(avcodeclock);
00881 silence_ffmpeg_logging = true;
00882 int retval = avformat_find_stream_info(ic, NULL);
00883 silence_ffmpeg_logging = false;
00884 return retval;
00885 }
00886
00899 int AvFormatDecoder::OpenFile(RingBuffer *rbuffer, bool novideo,
00900 char testbuf[kDecoderProbeBufferSize],
00901 int testbufsize)
00902 {
00903 CloseContext();
00904
00905 ringBuffer = rbuffer;
00906
00907 if (avfRingBuffer)
00908 delete avfRingBuffer;
00909 avfRingBuffer = new AVFRingBuffer(rbuffer);
00910
00911 AVInputFormat *fmt = NULL;
00912 QString fnames = ringBuffer->GetFilename();
00913 QByteArray fnamea = fnames.toAscii();
00914 const char *filename = fnamea.constData();
00915
00916 AVProbeData probe;
00917 probe.filename = filename;
00918 probe.buf = (unsigned char *)testbuf;
00919 if (testbufsize + AVPROBE_PADDING_SIZE <= kDecoderProbeBufferSize)
00920 probe.buf_size = testbufsize;
00921 else
00922 probe.buf_size = kDecoderProbeBufferSize - AVPROBE_PADDING_SIZE;
00923
00924 fmt = av_probe_input_format(&probe, true);
00925 if (!fmt)
00926 {
00927 LOG(VB_GENERAL, LOG_ERR, LOC +
00928 QString("Probe failed for file: \"%1\".").arg(filename));
00929 return -1;
00930 }
00931
00932 #if 0
00933 fmt->flags |= AVFMT_NOFILE;
00934 #endif
00935
00936 ic = avformat_alloc_context();
00937 if (!ic)
00938 {
00939 LOG(VB_GENERAL, LOG_ERR, LOC + "Could not allocate format context.");
00940 return -1;
00941 }
00942
00943 InitByteContext();
00944
00945 int err = avformat_open_input(&ic, filename, fmt, NULL);
00946 if (err < 0)
00947 {
00948 LOG(VB_GENERAL, LOG_ERR, LOC +
00949 QString("avformat err(%1) on avformat_open_input call.").arg(err));
00950 return -1;
00951 }
00952
00953 int ret = FindStreamInfo();
00954
00955
00956 if (!ringBuffer->StartFromBeginning())
00957 return -1;
00958 ringBuffer->IgnoreWaitStates(false);
00959
00960 if (ret < 0)
00961 {
00962 LOG(VB_GENERAL, LOG_ERR, LOC + "Could not find codec parameters. " +
00963 QString("file was \"%1\".").arg(filename));
00964 avformat_close_input(&ic);
00965 ic = NULL;
00966 return -1;
00967 }
00968 ic->streams_changed = HandleStreamChange;
00969 if (ringBuffer->IsDVD())
00970 ic->streams_changed = HandleDVDStreamChange;
00971 else if (ringBuffer->IsBD())
00972 ic->streams_changed = HandleBDStreamChange;
00973
00974 ic->stream_change_data = this;
00975
00976 fmt->flags &= ~AVFMT_NOFILE;
00977
00978 if (!livetv && !ringBuffer->IsDisc())
00979 {
00980
00981
00982 av_update_stream_timings_video(ic);
00983 }
00984
00985
00986 ret = ScanStreams(novideo);
00987 if (-1 == ret)
00988 return ret;
00989
00990 AutoSelectTracks();
00991
00992 #ifdef USING_MHEG
00993 {
00994 int initialAudio = -1, initialVideo = -1;
00995 if (itv || (itv = m_parent->GetInteractiveTV()))
00996 itv->GetInitialStreams(initialAudio, initialVideo);
00997 if (initialAudio >= 0)
00998 SetAudioByComponentTag(initialAudio);
00999 if (initialVideo >= 0)
01000 SetVideoByComponentTag(initialVideo);
01001 }
01002 #endif // USING_MHEG
01003
01004
01005 if (!recordingHasPositionMap && !is_db_ignored)
01006 {
01007 if ((m_playbackinfo) || livetv || watchingrecording)
01008 {
01009 recordingHasPositionMap |= SyncPositionMap();
01010 if (recordingHasPositionMap && !livetv && !watchingrecording)
01011 {
01012 hasFullPositionMap = true;
01013 gopset = true;
01014 }
01015 }
01016 }
01017
01018
01019
01020 int64_t dur = 0, frames = 0;
01021
01022 if (m_playbackinfo)
01023 {
01024 dur = m_playbackinfo->QueryTotalDuration();
01025 dur /= 1000000;
01026 frames = m_playbackinfo->QueryTotalFrames();
01027 }
01028
01029 if (dur == 0)
01030 {
01031 if ((ic->duration == (int64_t)AV_NOPTS_VALUE) &&
01032 (!livetv && !ringBuffer->IsDisc()))
01033 av_estimate_timings(ic, 0);
01034
01035 dur = ic->duration / (int64_t)AV_TIME_BASE;
01036 }
01037
01038 if (dur > 0 && !livetv && !watchingrecording)
01039 {
01040 m_parent->SetDuration((int)dur);
01041 }
01042
01043
01044 if (!recordingHasPositionMap && !livetv)
01045 {
01046 LOG(VB_PLAYBACK, LOG_INFO, LOC +
01047 "Recording has no position -- using libavformat seeking.");
01048
01049 if (dur > 0)
01050 {
01051 m_parent->SetFileLength((int)(dur), (int)(dur * fps));
01052 }
01053 else
01054 {
01055
01056 float bytespersec = (float)bitrate / 8 / 2;
01057 float secs = ringBuffer->GetRealFileSize() * 1.0 / bytespersec;
01058 m_parent->SetFileLength((int)(secs), (int)(secs * fps));
01059 }
01060
01061
01062
01063
01064 keyframedist = 15;
01065 positionMapType = MARK_GOP_BYFRAME;
01066
01067 if (!strcmp(fmt->name, "avi"))
01068 {
01069
01070 keyframedist = 1;
01071 }
01072
01073 dontSyncPositionMap = true;
01074 ic->build_index = 1;
01075 }
01076
01077 else
01078 ic->build_index = 0;
01079
01080 av_dump_format(ic, 0, filename, 0);
01081
01082
01083 if (hasFullPositionMap)
01084 LOG(VB_PLAYBACK, LOG_INFO, LOC + "Position map found");
01085 else if (recordingHasPositionMap)
01086 LOG(VB_PLAYBACK, LOG_INFO, LOC + "Partial position map found");
01087 LOG(VB_PLAYBACK, LOG_INFO, LOC +
01088 QString("Successfully opened decoder for file: \"%1\". novideo(%2)")
01089 .arg(filename).arg(novideo));
01090
01091
01092 for (unsigned int i=0; i < ic->nb_chapters; i++)
01093 {
01094 int num = ic->chapters[i]->time_base.num;
01095 int den = ic->chapters[i]->time_base.den;
01096 int64_t start = ic->chapters[i]->start;
01097 long double total_secs = (long double)start * (long double)num /
01098 (long double)den;
01099 int hours = (int)total_secs / 60 / 60;
01100 int minutes = ((int)total_secs / 60) - (hours * 60);
01101 double secs = (double)total_secs -
01102 (double)(hours * 60 * 60 + minutes * 60);
01103 long long framenum = (long long)(total_secs * fps);
01104 LOG(VB_PLAYBACK, LOG_INFO, LOC +
01105 QString("Chapter %1 found @ [%2:%3:%4]->%5")
01106 .arg(QString().sprintf("%02d", i + 1))
01107 .arg(QString().sprintf("%02d", hours))
01108 .arg(QString().sprintf("%02d", minutes))
01109 .arg(QString().sprintf("%06.3f", secs))
01110 .arg(framenum));
01111 }
01112
01113 if (getenv("FORCE_DTS_TIMESTAMPS"))
01114 force_dts_timestamps = true;
01115
01116
01117 return recordingHasPositionMap;
01118 }
01119
01120 float AvFormatDecoder::normalized_fps(AVStream *stream, AVCodecContext *enc)
01121 {
01122 float fps, avg_fps, codec_fps, container_fps, estimated_fps;
01123 avg_fps = codec_fps = container_fps = estimated_fps = 0.0f;
01124
01125 if (stream->avg_frame_rate.den && stream->avg_frame_rate.num)
01126 avg_fps = av_q2d(stream->avg_frame_rate);
01127
01128 if (enc->time_base.den && enc->time_base.num)
01129 codec_fps = 1.0f / av_q2d(enc->time_base) / enc->ticks_per_frame;
01130
01131 if (codec_fps > 121.0f && (enc->time_base.den > 10000) &&
01132 (enc->time_base.num == 1))
01133 {
01134 enc->time_base.num = 1001;
01135 if (av_q2d(enc->time_base) > 0)
01136 codec_fps = 1.0f / av_q2d(enc->time_base);
01137 }
01138 if (stream->time_base.den && stream->time_base.num)
01139 container_fps = 1.0f / av_q2d(stream->time_base);
01140 if (stream->r_frame_rate.den && stream->r_frame_rate.num)
01141 estimated_fps = av_q2d(stream->r_frame_rate);
01142
01143
01144
01145 if ((QString(ic->iformat->name).contains("matroska") ||
01146 QString(ic->iformat->name).contains("mov")) &&
01147 avg_fps < 121.0f && avg_fps > 3.0f)
01148 fps = avg_fps;
01149 else if (QString(ic->iformat->name).contains("avi") &&
01150 container_fps < 121.0f && container_fps > 3.0f)
01151 fps = container_fps;
01152 else if (codec_fps < 121.0f && codec_fps > 3.0f)
01153 fps = codec_fps;
01154 else if (container_fps < 121.0f && container_fps > 3.0f)
01155 fps = container_fps;
01156 else if (estimated_fps < 121.0f && estimated_fps > 3.0f)
01157 fps = estimated_fps;
01158 else if (avg_fps < 121.0f && avg_fps > 3.0f)
01159 fps = avg_fps;
01160 else
01161 fps = 30000.0f / 1001.0f;
01162
01163 if (fps != m_fps)
01164 {
01165 LOG(VB_PLAYBACK, LOG_INFO, LOC +
01166 QString("Selected FPS is %1 (avg %2 codec %3 "
01167 "container %4 estimated %5)").arg(fps).arg(avg_fps)
01168 .arg(codec_fps).arg(container_fps).arg(estimated_fps));
01169 m_fps = fps;
01170 }
01171
01172 return fps;
01173 }
01174
01175 static bool IS_VDPAU_PIX_FMT(enum PixelFormat fmt)
01176 {
01177 return
01178 fmt == PIX_FMT_VDPAU_H264 ||
01179 fmt == PIX_FMT_VDPAU_MPEG1 ||
01180 fmt == PIX_FMT_VDPAU_MPEG2 ||
01181 fmt == PIX_FMT_VDPAU_MPEG4 ||
01182 fmt == PIX_FMT_VDPAU_WMV3 ||
01183 fmt == PIX_FMT_VDPAU_VC1;
01184 }
01185
01186 static enum PixelFormat get_format_vdpau(struct AVCodecContext *avctx,
01187 const enum PixelFormat *fmt)
01188 {
01189 int i = 0;
01190
01191 for(i=0; fmt[i]!=PIX_FMT_NONE; i++)
01192 if (IS_VDPAU_PIX_FMT(fmt[i]))
01193 break;
01194
01195 return fmt[i];
01196 }
01197
01198
01199 static enum PixelFormat get_format_dxva2(struct AVCodecContext *,
01200 const enum PixelFormat *) MUNUSED;
01201
01202 enum PixelFormat get_format_dxva2(struct AVCodecContext *avctx,
01203 const enum PixelFormat *fmt)
01204 {
01205 if (!fmt)
01206 return PIX_FMT_NONE;
01207 int i = 0;
01208 for (; fmt[i] != PIX_FMT_NONE ; i++)
01209 if (PIX_FMT_DXVA2_VLD == fmt[i])
01210 break;
01211 return fmt[i];
01212 }
01213
01214 static bool IS_VAAPI_PIX_FMT(enum PixelFormat fmt)
01215 {
01216 return fmt == PIX_FMT_VAAPI_MOCO ||
01217 fmt == PIX_FMT_VAAPI_IDCT ||
01218 fmt == PIX_FMT_VAAPI_VLD;
01219 }
01220
01221
01222 static enum PixelFormat get_format_vaapi(struct AVCodecContext *,
01223 const enum PixelFormat *) MUNUSED;
01224
01225 enum PixelFormat get_format_vaapi(struct AVCodecContext *avctx,
01226 const enum PixelFormat *fmt)
01227 {
01228 if (!fmt)
01229 return PIX_FMT_NONE;
01230 int i = 0;
01231 for (; fmt[i] != PIX_FMT_NONE ; i++)
01232 if (IS_VAAPI_PIX_FMT(fmt[i]))
01233 break;
01234 return fmt[i];
01235 }
01236
01237 static bool IS_DR1_PIX_FMT(const enum PixelFormat fmt)
01238 {
01239 switch (fmt)
01240 {
01241 case PIX_FMT_YUV420P:
01242 case PIX_FMT_YUVJ420P:
01243 return true;
01244 default:
01245 return false;
01246 }
01247 }
01248
01249 void AvFormatDecoder::InitVideoCodec(AVStream *stream, AVCodecContext *enc,
01250 bool selectedStream)
01251 {
01252 LOG(VB_PLAYBACK, LOG_INFO, LOC +
01253 QString("InitVideoCodec() 0x%1 id(%2) type (%3).")
01254 .arg((uint64_t)enc,0,16)
01255 .arg(ff_codec_id_string(enc->codec_id))
01256 .arg(ff_codec_type_string(enc->codec_type)));
01257
01258 if (ringBuffer && ringBuffer->IsDVD())
01259 directrendering = false;
01260
01261 enc->opaque = (void *)this;
01262 enc->get_buffer = get_avf_buffer;
01263 enc->release_buffer = release_avf_buffer;
01264 enc->draw_horiz_band = NULL;
01265 enc->slice_flags = 0;
01266
01267 enc->err_recognition = AV_EF_COMPLIANT;
01268 enc->workaround_bugs = FF_BUG_AUTODETECT;
01269 enc->error_concealment = FF_EC_GUESS_MVS | FF_EC_DEBLOCK;
01270 enc->idct_algo = FF_IDCT_AUTO;
01271 enc->debug = 0;
01272 enc->error_rate = 0;
01273
01274 AVCodec *codec = avcodec_find_decoder(enc->codec_id);
01275
01276 if (codec_is_vdpau(video_codec_id) && !CODEC_IS_VDPAU(codec))
01277 codec = find_vdpau_decoder(codec, enc->codec_id);
01278
01279 if (selectedStream)
01280 {
01281 directrendering = true;
01282 if (!gCoreContext->GetNumSetting("DecodeExtraAudio", 0) &&
01283 !CODEC_IS_HWACCEL(codec, enc))
01284 {
01285 SetLowBuffers(false);
01286 }
01287 }
01288
01289 if (CODEC_IS_VDPAU(codec))
01290 {
01291 enc->get_buffer = get_avf_buffer_vdpau;
01292 enc->get_format = get_format_vdpau;
01293 enc->release_buffer = release_avf_buffer_vdpau;
01294 enc->draw_horiz_band = render_slice_vdpau;
01295 enc->slice_flags = SLICE_FLAG_CODED_ORDER | SLICE_FLAG_ALLOW_FIELD;
01296 }
01297 else if (CODEC_IS_DXVA2(codec, enc))
01298 {
01299 enc->get_buffer = get_avf_buffer_dxva2;
01300 enc->get_format = get_format_dxva2;
01301 enc->release_buffer = release_avf_buffer;
01302 }
01303 else if (CODEC_IS_VAAPI(codec, enc))
01304 {
01305 enc->get_buffer = get_avf_buffer_vaapi;
01306 enc->get_format = get_format_vaapi;
01307 enc->release_buffer = release_avf_buffer;
01308 enc->slice_flags = SLICE_FLAG_CODED_ORDER | SLICE_FLAG_ALLOW_FIELD;
01309 }
01310 else if (codec && codec->capabilities & CODEC_CAP_DR1)
01311 {
01312 enc->flags |= CODEC_FLAG_EMU_EDGE;
01313 }
01314 else
01315 {
01316 if (selectedStream)
01317 directrendering = false;
01318 LOG(VB_PLAYBACK, LOG_INFO, LOC +
01319 QString("Using software scaling to convert pixel format %1 for "
01320 "codec %2").arg(enc->pix_fmt)
01321 .arg(ff_codec_id_string(enc->codec_id)));
01322 }
01323
01324 if (FlagIsSet(kDecodeLowRes) || FlagIsSet(kDecodeSingleThreaded) ||
01325 FlagIsSet(kDecodeFewBlocks) || FlagIsSet(kDecodeNoLoopFilter) ||
01326 FlagIsSet(kDecodeNoDecode))
01327 {
01328 enc->flags2 |= CODEC_FLAG2_FAST;
01329
01330 if ((CODEC_ID_MPEG2VIDEO == codec->id) ||
01331 (CODEC_ID_MPEG1VIDEO == codec->id))
01332 {
01333 if (FlagIsSet(kDecodeFewBlocks))
01334 {
01335 uint total_blocks = (enc->height+15) / 16;
01336 enc->skip_top = (total_blocks+3) / 4;
01337 enc->skip_bottom = (total_blocks+3) / 4;
01338 }
01339
01340 if (FlagIsSet(kDecodeLowRes))
01341 enc->lowres = 2;
01342 }
01343 else if (CODEC_ID_H264 == codec->id)
01344 {
01345 if (FlagIsSet(kDecodeNoLoopFilter))
01346 {
01347 enc->flags &= ~CODEC_FLAG_LOOP_FILTER;
01348 enc->skip_loop_filter = AVDISCARD_ALL;
01349 }
01350 }
01351
01352 if (FlagIsSet(kDecodeNoDecode))
01353 {
01354 enc->skip_idct = AVDISCARD_ALL;
01355 }
01356 }
01357
01358 if (selectedStream)
01359 {
01360 fps = normalized_fps(stream, enc);
01361 QSize dim = get_video_dim(*enc);
01362 int width = current_width = dim.width();
01363 int height = current_height = dim.height();
01364 current_aspect = get_aspect(*enc);
01365
01366 if (!width || !height)
01367 {
01368 LOG(VB_PLAYBACK, LOG_INFO, LOC +
01369 "InitVideoCodec invalid dimensions, resetting decoder.");
01370 width = 640;
01371 height = 480;
01372 fps = 29.97f;
01373 current_aspect = 4.0f / 3.0f;
01374 }
01375
01376 m_parent->SetKeyframeDistance(keyframedist);
01377 m_parent->SetVideoParams(width, height, fps, kScan_Detect);
01378 if (LCD *lcd = LCD::Get())
01379 {
01380 LCDVideoFormatSet video_format;
01381
01382 switch (enc->codec_id)
01383 {
01384 case CODEC_ID_H263:
01385 case CODEC_ID_MPEG4:
01386 case CODEC_ID_MSMPEG4V1:
01387 case CODEC_ID_MSMPEG4V2:
01388 case CODEC_ID_MSMPEG4V3:
01389 case CODEC_ID_H263P:
01390 case CODEC_ID_H263I:
01391 video_format = VIDEO_DIVX;
01392 break;
01393 case CODEC_ID_WMV1:
01394 case CODEC_ID_WMV2:
01395 video_format = VIDEO_WMV;
01396 break;
01397 #if 0
01398 case CODEC_ID_XVID:
01399 video_format = VIDEO_XVID;
01400 break;
01401 #endif
01402 default:
01403 video_format = VIDEO_MPG;
01404 break;
01405 }
01406
01407 lcd->setVideoFormatLEDs(video_format, true);
01408
01409 if(height >= 720)
01410 lcd->setVariousLEDs(VARIOUS_HDTV, true);
01411 else
01412 lcd->setVariousLEDs(VARIOUS_HDTV, false);
01413 }
01414 }
01415 }
01416
01417
01418
01419
01420 static int cc608_parity(uint8_t byte)
01421 {
01422 int ones = 0;
01423
01424 for (int i = 0; i < 7; i++)
01425 {
01426 if (byte & (1 << i))
01427 ones++;
01428 }
01429
01430 return ones & 1;
01431 }
01432
01433
01434
01435
01436 static void cc608_build_parity_table(int *parity_table)
01437 {
01438 uint8_t byte;
01439 int parity_v;
01440 for (byte = 0; byte <= 127; byte++)
01441 {
01442 parity_v = cc608_parity(byte);
01443
01444 parity_table[byte] = parity_v;
01445 parity_table[byte | 0x80] = !parity_v;
01446 }
01447 }
01448
01449
01450
01451
01452 static int cc608_good_parity(const int *parity_table, uint16_t data)
01453 {
01454 int ret = parity_table[data & 0xff] && parity_table[(data & 0xff00) >> 8];
01455 if (!ret)
01456 {
01457 LOG(VB_VBI, LOG_ERR, LOC +
01458 QString("VBI: Bad parity in EIA-608 data (%1)") .arg(data,0,16));
01459 }
01460 return ret;
01461 }
01462
01463 void AvFormatDecoder::ScanATSCCaptionStreams(int av_index)
01464 {
01465 memset(ccX08_in_pmt, 0, sizeof(ccX08_in_pmt));
01466 pmt_tracks.clear();
01467 pmt_track_types.clear();
01468
01469
01470 if (!ic->cur_pmt_sect)
01471 {
01472 LOG(VB_GENERAL, LOG_DEBUG, LOC +
01473 "ScanATSCCaptionStreams() called with no PMT");
01474 return;
01475 }
01476
01477 const PESPacket pes = PESPacket::ViewData(ic->cur_pmt_sect);
01478 const PSIPTable psip(pes);
01479 const ProgramMapTable pmt(psip);
01480
01481 uint i;
01482 for (i = 0; i < pmt.StreamCount(); i++)
01483 {
01484
01485
01486
01487 if (pmt.IsVideo(i, "dvb"))
01488 break;
01489 }
01490
01491 if (!pmt.IsVideo(i, "dvb"))
01492 return;
01493
01494 desc_list_t desc_list = MPEGDescriptor::ParseOnlyInclude(
01495 pmt.StreamInfo(i), pmt.StreamInfoLength(i),
01496 DescriptorID::caption_service);
01497
01498 const desc_list_t desc_list2 = MPEGDescriptor::ParseOnlyInclude(
01499 pmt.ProgramInfo(), pmt.ProgramInfoLength(),
01500 DescriptorID::caption_service);
01501
01502 desc_list.insert(desc_list.end(), desc_list2.begin(), desc_list2.end());
01503
01504 for (uint j = 0; j < desc_list.size(); j++)
01505 {
01506 const CaptionServiceDescriptor csd(desc_list[j]);
01507 for (uint k = 0; k < csd.ServicesCount(); k++)
01508 {
01509 int lang = csd.CanonicalLanguageKey(k);
01510 int type = csd.Type(k) ? 1 : 0;
01511 if (type)
01512 {
01513 StreamInfo si(av_index, lang, 0,
01514 csd.CaptionServiceNumber(k),
01515 csd.EasyReader(k),
01516 csd.WideAspectRatio(k));
01517 uint key = csd.CaptionServiceNumber(k) + 4;
01518 ccX08_in_pmt[key] = true;
01519 pmt_tracks.push_back(si);
01520 pmt_track_types.push_back(kTrackTypeCC708);
01521 }
01522 else
01523 {
01524 int line21 = csd.Line21Field(k) ? 3 : 1;
01525 StreamInfo si(av_index, lang, 0, line21, 0);
01526 ccX08_in_pmt[line21-1] = true;
01527 pmt_tracks.push_back(si);
01528 pmt_track_types.push_back(kTrackTypeCC608);
01529 }
01530 }
01531 }
01532 }
01533
01534 void AvFormatDecoder::UpdateATSCCaptionTracks(void)
01535 {
01536 tracks[kTrackTypeCC608].clear();
01537 tracks[kTrackTypeCC708].clear();
01538 memset(ccX08_in_tracks, 0, sizeof(ccX08_in_tracks));
01539
01540 uint pidx = 0, sidx = 0;
01541 map<int,uint> lang_cc_cnt[2];
01542 while (true)
01543 {
01544 bool pofr = pidx >= (uint)pmt_tracks.size();
01545 bool sofr = sidx >= (uint)stream_tracks.size();
01546 if (pofr && sofr)
01547 break;
01548
01549
01550
01551
01552 StreamInfo const *si = NULL;
01553 int type = 0;
01554 bool isp = true;
01555
01556 if (pofr && !sofr)
01557 isp = false;
01558 else if (!pofr && sofr)
01559 isp = true;
01560 else if (stream_tracks[sidx] < pmt_tracks[pidx])
01561 isp = false;
01562
01563 if (isp)
01564 {
01565 si = &pmt_tracks[pidx];
01566 type = kTrackTypeCC708 == pmt_track_types[pidx] ? 1 : 0;
01567 pidx++;
01568 }
01569 else
01570 {
01571 si = &stream_tracks[sidx];
01572 type = kTrackTypeCC708 == stream_track_types[sidx] ? 1 : 0;
01573 sidx++;
01574 }
01575
01576 StreamInfo nsi(*si);
01577 int lang_indx = lang_cc_cnt[type][nsi.language];
01578 lang_cc_cnt[type][nsi.language]++;
01579 nsi.language_index = lang_indx;
01580 tracks[(type) ? kTrackTypeCC708 : kTrackTypeCC608].push_back(nsi);
01581 int key = (int)nsi.stream_id + ((type) ? 4 : -1);
01582 if (key < 0)
01583 {
01584 LOG(VB_GENERAL, LOG_ERR, LOC + "in_tracks key too small");
01585 }
01586 else
01587 {
01588 ccX08_in_tracks[key] = true;
01589 }
01590 LOG(VB_PLAYBACK, LOG_INFO, LOC +
01591 QString("%1 caption service #%2 is in the %3 language.")
01592 .arg((type) ? "EIA-708" : "EIA-608")
01593 .arg(nsi.stream_id)
01594 .arg(iso639_key_toName(nsi.language)));
01595 }
01596 }
01597
01598 void AvFormatDecoder::ScanTeletextCaptions(int av_index)
01599 {
01600
01601 if (!ic->cur_pmt_sect || tracks[kTrackTypeTeletextCaptions].size())
01602 return;
01603
01604 const PESPacket pes = PESPacket::ViewData(ic->cur_pmt_sect);
01605 const PSIPTable psip(pes);
01606 const ProgramMapTable pmt(psip);
01607
01608 for (uint i = 0; i < pmt.StreamCount(); i++)
01609 {
01610 if (pmt.StreamType(i) != StreamID::PrivData)
01611 continue;
01612
01613 const desc_list_t desc_list = MPEGDescriptor::ParseOnlyInclude(
01614 pmt.StreamInfo(i), pmt.StreamInfoLength(i),
01615 DescriptorID::teletext);
01616
01617 for (uint j = 0; j < desc_list.size(); j++)
01618 {
01619 const TeletextDescriptor td(desc_list[j]);
01620 for (uint k = 0; k < td.StreamCount(); k++)
01621 {
01622 int type = td.TeletextType(k);
01623 int language = td.CanonicalLanguageKey(k);
01624 int magazine = td.TeletextMagazineNum(k);
01625 if (magazine == 0)
01626 magazine = 8;
01627 int pagenum = td.TeletextPageNum(k);
01628 int lang_idx = (magazine << 8) | pagenum;
01629 StreamInfo si(av_index, language, lang_idx, 0, 0);
01630 if (type == 2 || type == 1)
01631 {
01632 TrackType track = (type == 2) ? kTrackTypeTeletextCaptions :
01633 kTrackTypeTeletextMenu;
01634 tracks[track].push_back(si);
01635 LOG(VB_PLAYBACK, LOG_INFO, LOC +
01636 QString("Teletext stream #%1 (%2) is in the %3 language"
01637 " on page %4 %5.")
01638 .arg(k).arg((type == 2) ? "Caption" : "Menu")
01639 .arg(iso639_key_toName(language))
01640 .arg(magazine).arg(pagenum));
01641 }
01642 }
01643 }
01644
01645
01646 if (tracks[kTrackTypeTeletextCaptions].size())
01647 break;
01648 }
01649 }
01650
01651 void AvFormatDecoder::ScanRawTextCaptions(int av_stream_index)
01652 {
01653 AVDictionaryEntry *metatag =
01654 av_dict_get(ic->streams[av_stream_index]->metadata, "language", NULL,
01655 0);
01656 int lang = metatag ? get_canonical_lang(metatag->value) :
01657 iso639_str3_to_key("und");
01658 LOG(VB_PLAYBACK, LOG_INFO, LOC +
01659 QString("Text Subtitle track #%1 is A/V stream #%2 "
01660 "and is in the %3 language(%4).")
01661 .arg(tracks[kTrackTypeRawText].size()).arg(av_stream_index)
01662 .arg(iso639_key_toName(lang)).arg(lang));
01663 StreamInfo si(av_stream_index, lang, 0, 0, 0);
01664 tracks[kTrackTypeRawText].push_back(si);
01665 }
01666
01671 void AvFormatDecoder::ScanDSMCCStreams(void)
01672 {
01673 if (!ic || !ic->cur_pmt_sect)
01674 return;
01675
01676 if (!itv && ! (itv = m_parent->GetInteractiveTV()))
01677 return;
01678
01679 const PESPacket pes = PESPacket::ViewData(ic->cur_pmt_sect);
01680 const PSIPTable psip(pes);
01681 const ProgramMapTable pmt(psip);
01682
01683 for (uint i = 0; i < pmt.StreamCount(); i++)
01684 {
01685 if (! StreamID::IsObjectCarousel(pmt.StreamType(i)))
01686 continue;
01687
01688 const desc_list_t desc_list = MPEGDescriptor::ParseOnlyInclude(
01689 pmt.StreamInfo(i), pmt.StreamInfoLength(i),
01690 DescriptorID::data_broadcast_id);
01691
01692 for (uint j = 0; j < desc_list.size(); j++)
01693 {
01694 const unsigned char *desc = desc_list[j];
01695 desc++;
01696 uint length = *desc++;
01697 const unsigned char *endDesc = desc+length;
01698 uint dataBroadcastId = desc[0]<<8 | desc[1];
01699 if (dataBroadcastId != 0x0106)
01700 continue;
01701 desc += 2;
01702 while (desc != endDesc)
01703 {
01704 uint appTypeCode = desc[0]<<8 | desc[1];
01705 desc += 3;
01706 uint appSpecDataLen = *desc++;
01707 #ifdef USING_MHEG
01708 if (appTypeCode == 0x101)
01709 {
01710 const unsigned char *subDescEnd = desc + appSpecDataLen;
01711 while (desc < subDescEnd)
01712 {
01713 uint sub_desc_tag = *desc++;
01714 uint sub_desc_len = *desc++;
01715
01716 if (sub_desc_tag == 1)
01717 itv->SetNetBootInfo(desc, sub_desc_len);
01718 desc += sub_desc_len;
01719 }
01720 }
01721 else
01722 #else
01723 (void) appTypeCode;
01724 #endif // USING_MHEG
01725 {
01726 desc += appSpecDataLen;
01727 }
01728 }
01729 }
01730 }
01731 }
01732
01733 int AvFormatDecoder::ScanStreams(bool novideo)
01734 {
01735 bool unknownbitrate = false;
01736 int scanerror = 0;
01737 bitrate = 0;
01738 fps = 0;
01739
01740 tracks[kTrackTypeAttachment].clear();
01741 tracks[kTrackTypeAudio].clear();
01742 tracks[kTrackTypeSubtitle].clear();
01743 tracks[kTrackTypeTeletextCaptions].clear();
01744 tracks[kTrackTypeTeletextMenu].clear();
01745 tracks[kTrackTypeRawText].clear();
01746 tracks[kTrackTypeVideo].clear();
01747 selectedTrack[kTrackTypeVideo].av_stream_index = -1;
01748
01749 map<int,uint> lang_sub_cnt;
01750 uint subtitleStreamCount = 0;
01751 map<int,uint> lang_aud_cnt;
01752 uint audioStreamCount = 0;
01753
01754 if (ringBuffer && ringBuffer->IsDVD() &&
01755 ringBuffer->DVD()->AudioStreamsChanged())
01756 {
01757 ringBuffer->DVD()->AudioStreamsChanged(false);
01758 RemoveAudioStreams();
01759 }
01760
01761 for (uint i = 0; i < ic->nb_streams; i++)
01762 {
01763 AVCodecContext *enc = ic->streams[i]->codec;
01764 LOG(VB_PLAYBACK, LOG_INFO, LOC +
01765 QString("Stream #%1, has id 0x%2 codec id %3, "
01766 "type %4, bitrate %5 at 0x%6")
01767 .arg(i).arg((uint64_t)ic->streams[i]->id,0,16)
01768 .arg(ff_codec_id_string(enc->codec_id))
01769 .arg(ff_codec_type_string(enc->codec_type))
01770 .arg(enc->bit_rate).arg((uint64_t)ic->streams[i],0,16));
01771
01772 switch (enc->codec_type)
01773 {
01774 case AVMEDIA_TYPE_VIDEO:
01775 {
01776
01777 if (!enc->codec_id)
01778 {
01779 LOG(VB_GENERAL, LOG_ERR, LOC +
01780 QString("Stream #%1 has an unknown video "
01781 "codec id, skipping.").arg(i));
01782 continue;
01783 }
01784
01785 codec_is_mpeg = CODEC_IS_FFMPEG_MPEG(enc->codec_id);
01786
01787
01788
01789
01790 if (enc->bit_rate == 0)
01791 {
01792 enc->bit_rate = 500000;
01793 unknownbitrate = true;
01794 }
01795
01796 StreamInfo si(i, 0, 0, 0, 0);
01797 tracks[kTrackTypeVideo].push_back(si);
01798 bitrate += enc->bit_rate;
01799 if (novideo)
01800 break;
01801
01802 delete private_dec;
01803 private_dec = NULL;
01804 m_h264_parser->Reset();
01805
01806 QSize dim = get_video_dim(*enc);
01807 uint width = max(dim.width(), 16);
01808 uint height = max(dim.height(), 16);
01809 QString dec = "ffmpeg";
01810 uint thread_count = 1;
01811
01812 if (!is_db_ignored)
01813 {
01814 VideoDisplayProfile vdp;
01815 vdp.SetInput(QSize(width, height));
01816 dec = vdp.GetDecoder();
01817 thread_count = vdp.GetMaxCPUs();
01818 bool skip_loop_filter = vdp.IsSkipLoopEnabled();
01819 if (!skip_loop_filter)
01820 {
01821 enc->skip_loop_filter = AVDISCARD_NONKEY;
01822 }
01823 }
01824
01825 video_codec_id = kCodec_NONE;
01826 int version = mpeg_version(enc->codec_id);
01827 if (version)
01828 video_codec_id = (MythCodecID)(kCodec_MPEG1 + version - 1);
01829
01830 if (version)
01831 {
01832 #if defined(USING_VDPAU)
01833
01834
01835
01836
01837
01838 if (enc->codec_id == CODEC_ID_MPEG1VIDEO)
01839 enc->codec_id = CODEC_ID_MPEG2VIDEO;
01840
01841 #endif // USING_VDPAU
01842 #ifdef USING_VDPAU
01843 MythCodecID vdpau_mcid;
01844 vdpau_mcid = VideoOutputVDPAU::GetBestSupportedCodec(
01845 width, height, dec,
01846 mpeg_version(enc->codec_id),
01847 !FlagIsSet(kDecodeAllowGPU));
01848
01849 if (vdpau_mcid >= video_codec_id)
01850 {
01851 enc->codec_id = (CodecID) myth2av_codecid(vdpau_mcid);
01852 video_codec_id = vdpau_mcid;
01853 }
01854 #endif // USING_VDPAU
01855 #ifdef USING_GLVAAPI
01856 MythCodecID vaapi_mcid;
01857 PixelFormat pix_fmt = PIX_FMT_YUV420P;
01858 vaapi_mcid = VideoOutputOpenGLVAAPI::GetBestSupportedCodec(
01859 width, height, dec, mpeg_version(enc->codec_id),
01860 !FlagIsSet(kDecodeAllowGPU), pix_fmt);
01861
01862 if (vaapi_mcid >= video_codec_id)
01863 {
01864 enc->codec_id = (CodecID)myth2av_codecid(vaapi_mcid);
01865 video_codec_id = vaapi_mcid;
01866 if (FlagIsSet(kDecodeAllowGPU) &&
01867 codec_is_vaapi(video_codec_id))
01868 {
01869 enc->pix_fmt = pix_fmt;
01870 }
01871 }
01872 #endif // USING_GLVAAPI
01873 #ifdef USING_DXVA2
01874 MythCodecID dxva2_mcid;
01875 PixelFormat pix_fmt = PIX_FMT_YUV420P;
01876 dxva2_mcid = VideoOutputD3D::GetBestSupportedCodec(
01877 width, height, dec, mpeg_version(enc->codec_id),
01878 !FlagIsSet(kDecodeAllowGPU), pix_fmt);
01879
01880 if (dxva2_mcid >= video_codec_id)
01881 {
01882 enc->codec_id = (CodecID)myth2av_codecid(dxva2_mcid);
01883 video_codec_id = dxva2_mcid;
01884 if (FlagIsSet(kDecodeAllowGPU) &&
01885 codec_is_dxva2(video_codec_id))
01886 {
01887 enc->pix_fmt = pix_fmt;
01888 }
01889 }
01890 #endif // USING_DXVA2
01891 }
01892
01893
01894 if (video_codec_id == kCodec_NONE)
01895 {
01896 LOG(VB_GENERAL, LOG_ERR, LOC +
01897 "Unknown video codec - defaulting to MPEG2");
01898 video_codec_id = kCodec_MPEG2;
01899 }
01900
01901 if (enc->codec)
01902 {
01903 LOG(VB_GENERAL, LOG_WARNING, LOC +
01904 QString("Warning, video codec 0x%1 id(%2) type (%3) "
01905 "already open.")
01906 .arg((uint64_t)enc,0,16)
01907 .arg(ff_codec_id_string(enc->codec_id))
01908 .arg(ff_codec_type_string(enc->codec_type)));
01909 }
01910
01911
01912
01913 if (selectedTrack[kTrackTypeVideo].av_stream_index < 0)
01914 selectedTrack[kTrackTypeVideo] = si;
01915
01916
01917
01918 if (selectedTrack[kTrackTypeVideo].av_stream_index == (int) i)
01919 {
01920 private_dec = PrivateDecoder::Create(dec, playerFlags, enc);
01921 if (private_dec)
01922 thread_count = 1;
01923 }
01924
01925 if (!codec_is_std(video_codec_id))
01926 thread_count = 1;
01927
01928 if (FlagIsSet(kDecodeSingleThreaded))
01929 thread_count = 1;
01930
01931 LOG(VB_PLAYBACK, LOG_INFO, LOC +
01932 QString("Using %1 CPUs for decoding")
01933 .arg(HAVE_THREADS ? thread_count : 1));
01934
01935 if (HAVE_THREADS)
01936 enc->thread_count = thread_count;
01937
01938 InitVideoCodec(ic->streams[i], enc,
01939 selectedTrack[kTrackTypeVideo].av_stream_index == (int) i);
01940
01941 ScanATSCCaptionStreams(i);
01942 UpdateATSCCaptionTracks();
01943
01944 LOG(VB_PLAYBACK, LOG_INFO, LOC +
01945 QString("Using %1 for video decoding")
01946 .arg(GetCodecDecoderName()));
01947
01948 break;
01949 }
01950 case AVMEDIA_TYPE_AUDIO:
01951 {
01952 if (enc->codec)
01953 {
01954 LOG(VB_GENERAL, LOG_WARNING, LOC +
01955 QString("Warning, audio codec 0x%1 id(%2) "
01956 "type (%3) already open, leaving it alone.")
01957 .arg((uint64_t)enc,0,16)
01958 .arg(ff_codec_id_string(enc->codec_id))
01959 .arg(ff_codec_type_string(enc->codec_type)));
01960 }
01961
01962 LOG(VB_GENERAL, LOG_INFO, LOC +
01963 QString("codec %1 has %2 channels")
01964 .arg(ff_codec_id_string(enc->codec_id))
01965 .arg(enc->channels));
01966
01967 bitrate += enc->bit_rate;
01968 break;
01969 }
01970 case AVMEDIA_TYPE_SUBTITLE:
01971 {
01972 if (enc->codec_id == CODEC_ID_DVB_TELETEXT)
01973 ScanTeletextCaptions(i);
01974 if (enc->codec_id == CODEC_ID_TEXT)
01975 ScanRawTextCaptions(i);
01976 bitrate += enc->bit_rate;
01977
01978 LOG(VB_PLAYBACK, LOG_INFO, LOC + QString("subtitle codec (%1)")
01979 .arg(ff_codec_type_string(enc->codec_type)));
01980 break;
01981 }
01982 case AVMEDIA_TYPE_DATA:
01983 {
01984 ScanTeletextCaptions(i);
01985 bitrate += enc->bit_rate;
01986 LOG(VB_PLAYBACK, LOG_INFO, LOC + QString("data codec (%1)")
01987 .arg(ff_codec_type_string(enc->codec_type)));
01988 break;
01989 }
01990 case AVMEDIA_TYPE_ATTACHMENT:
01991 {
01992 if (enc->codec_id == CODEC_ID_TTF)
01993 tracks[kTrackTypeAttachment].push_back(
01994 StreamInfo(i, 0, 0, ic->streams[i]->id, 0));
01995 bitrate += enc->bit_rate;
01996 LOG(VB_PLAYBACK, LOG_INFO, LOC +
01997 QString("Attachment codec (%1)")
01998 .arg(ff_codec_type_string(enc->codec_type)));
01999 break;
02000 }
02001 default:
02002 {
02003 bitrate += enc->bit_rate;
02004 LOG(VB_PLAYBACK, LOG_ERR, LOC +
02005 QString("Unknown codec type (%1)")
02006 .arg(ff_codec_type_string(enc->codec_type)));
02007 break;
02008 }
02009 }
02010
02011 if (enc->codec_type != AVMEDIA_TYPE_AUDIO &&
02012 enc->codec_type != AVMEDIA_TYPE_VIDEO &&
02013 enc->codec_type != AVMEDIA_TYPE_SUBTITLE)
02014 continue;
02015
02016
02017 if (enc->codec_type == AVMEDIA_TYPE_SUBTITLE &&
02018 (enc->codec_id == CODEC_ID_DVB_TELETEXT ||
02019 enc->codec_id == CODEC_ID_TEXT))
02020 continue;
02021
02022 LOG(VB_PLAYBACK, LOG_INFO, LOC + QString("Looking for decoder for %1")
02023 .arg(ff_codec_id_string(enc->codec_id)));
02024
02025 if (enc->codec_id == CODEC_ID_PROBE)
02026 {
02027 LOG(VB_GENERAL, LOG_ERR, LOC +
02028 QString("Probing of stream #%1 unsuccesful, ignoring.").arg(i));
02029 continue;
02030 }
02031
02032 AVCodec *codec = avcodec_find_decoder(enc->codec_id);
02033 if (!codec)
02034 {
02035 LOG(VB_GENERAL, LOG_ERR, LOC +
02036 QString("Could not find decoder for codec (%1), ignoring.")
02037 .arg(ff_codec_id_string(enc->codec_id)));
02038
02039
02040
02041
02042 if (VERBOSE_LEVEL_CHECK(VB_LIBAV, LOG_ANY))
02043 {
02044 AVCodec *p = av_codec_next(NULL);
02045 int i = 1;
02046 while (p)
02047 {
02048 QString msg;
02049
02050 if (p->name[0] != '\0')
02051 msg = QString("Codec %1:").arg(p->name);
02052 else
02053 msg = QString("Codec %1, null name,").arg(i);
02054
02055 if (p->decode == NULL)
02056 msg += "decoder is null";
02057
02058 LOG(VB_LIBAV, LOG_INFO, LOC + msg);
02059
02060 if (p->id == enc->codec_id)
02061 {
02062 codec = p;
02063 break;
02064 }
02065
02066 LOG(VB_LIBAV, LOG_INFO, LOC +
02067 QString("Codec 0x%1 != 0x%2") .arg(p->id, 0, 16)
02068 .arg(enc->codec_id, 0, 16));
02069 p = av_codec_next(p);
02070 ++i;
02071 }
02072 }
02073 if (!codec)
02074 continue;
02075 }
02076
02077 else if (enc->codec_type == AVMEDIA_TYPE_VIDEO &&
02078 codec_is_vdpau(video_codec_id) && !CODEC_IS_VDPAU(codec))
02079 {
02080 codec = find_vdpau_decoder(codec, enc->codec_id);
02081 }
02082
02083 if (!enc->codec)
02084 {
02085 QMutexLocker locker(avcodeclock);
02086
02087 int open_val = avcodec_open2(enc, codec, NULL);
02088 if (open_val < 0)
02089 {
02090 LOG(VB_GENERAL, LOG_ERR, LOC +
02091 QString("Could not open codec 0x%1, id(%2) type(%3) "
02092 "aborting. reason %4").arg((uint64_t)enc,0,16)
02093 .arg(ff_codec_id_string(enc->codec_id))
02094 .arg(ff_codec_type_string(enc->codec_type))
02095 .arg(open_val));
02096
02097 ic = NULL;
02098 scanerror = -1;
02099 break;
02100 }
02101 else
02102 {
02103 LOG(VB_GENERAL, LOG_INFO, LOC +
02104 QString("Opened codec 0x%1, id(%2) type(%3)")
02105 .arg((uint64_t)enc,0,16)
02106 .arg(ff_codec_id_string(enc->codec_id))
02107 .arg(ff_codec_type_string(enc->codec_type)));
02108 }
02109 }
02110
02111 if (enc->codec_type == AVMEDIA_TYPE_SUBTITLE)
02112 {
02113 bool forced = ic->streams[i]->disposition & AV_DISPOSITION_FORCED;
02114 int lang = GetSubtitleLanguage(subtitleStreamCount, i);
02115 int lang_indx = lang_sub_cnt[lang]++;
02116 subtitleStreamCount++;
02117
02118 tracks[kTrackTypeSubtitle].push_back(
02119 StreamInfo(i, lang, lang_indx, ic->streams[i]->id, 0, 0, false, false, forced));
02120
02121 LOG(VB_PLAYBACK, LOG_INFO, LOC +
02122 QString("Subtitle track #%1 is A/V stream #%2 "
02123 "and is in the %3 language(%4).")
02124 .arg(tracks[kTrackTypeSubtitle].size()).arg(i)
02125 .arg(iso639_key_toName(lang)).arg(lang));
02126 }
02127
02128 if (enc->codec_type == AVMEDIA_TYPE_AUDIO)
02129 {
02130 int lang = GetAudioLanguage(audioStreamCount, i);
02131 int channels = ic->streams[i]->codec->channels;
02132 int lang_indx = lang_aud_cnt[lang]++;
02133 audioStreamCount++;
02134 AudioTrackType type = kAudioTypeNormal;
02135
02136 if (ic->streams[i]->codec->avcodec_dual_language)
02137 {
02138 tracks[kTrackTypeAudio].push_back(
02139 StreamInfo(i, lang, lang_indx, ic->streams[i]->id, channels,
02140 false, false, false, type));
02141 lang_indx = lang_aud_cnt[lang]++;
02142 tracks[kTrackTypeAudio].push_back(
02143 StreamInfo(i, lang, lang_indx, ic->streams[i]->id, channels,
02144 true, false, false, type));
02145 }
02146 else
02147 {
02148 int logical_stream_id;
02149 if (ringBuffer && ringBuffer->IsDVD())
02150 {
02151 logical_stream_id =
02152 ringBuffer->DVD()->GetAudioTrackNum(ic->streams[i]->id);
02153 type = (AudioTrackType)(ringBuffer->DVD()->GetAudioTrackType(ic->streams[i]->id));
02154 }
02155 else
02156 logical_stream_id = ic->streams[i]->id;
02157
02158 tracks[kTrackTypeAudio].push_back(
02159 StreamInfo(i, lang, lang_indx, logical_stream_id, channels,
02160 false, false, false, type));
02161 }
02162
02163 LOG(VB_AUDIO, LOG_INFO, LOC +
02164 QString("Audio Track #%1, with type %2 is A/V stream #%3 "
02165 "and has %4 channels in the %5 language(%6).")
02166 .arg(tracks[kTrackTypeAudio].size()).arg((int)type).arg(i)
02167 .arg(enc->channels)
02168 .arg(iso639_key_toName(lang)).arg(lang));
02169 }
02170 }
02171
02172 if (bitrate > 0)
02173 {
02174 bitrate = (bitrate + 999) / 1000;
02175 if (ringBuffer)
02176 ringBuffer->UpdateRawBitrate(bitrate);
02177 }
02178
02179
02180 if (ringBuffer)
02181 {
02182 ringBuffer->SetBufferSizeFactors(unknownbitrate,
02183 ic && QString(ic->iformat->name).contains("matroska"));
02184 }
02185
02186 PostProcessTracks();
02187
02188
02189 ResetTracks();
02190
02191
02192
02193 if (m_audio->HasAudioIn() && tracks[kTrackTypeAudio].empty())
02194 {
02195 m_audio->SetAudioParams(FORMAT_NONE, -1, -1, CODEC_ID_NONE, -1, false);
02196 m_audio->ReinitAudio();
02197 if (ringBuffer && ringBuffer->IsDVD())
02198 audioIn = AudioInfo();
02199 }
02200
02201
02202
02203 if (selectedTrack[kTrackTypeVideo].av_stream_index == -1)
02204 {
02205 LOG(VB_PLAYBACK, LOG_INFO, LOC +
02206 QString("No video track found/selected."));
02207 QString tvformat = gCoreContext->GetSetting("TVFormat").toLower();
02208 if (tvformat == "ntsc" || tvformat == "ntsc-jp" ||
02209 tvformat == "pal-m" || tvformat == "atsc")
02210 {
02211 fps = 29.97;
02212 m_parent->SetVideoParams(-1, -1, 29.97);
02213 }
02214 else
02215 {
02216 fps = 25.0;
02217 m_parent->SetVideoParams(-1, -1, 25.0);
02218 }
02219 }
02220
02221 if (m_parent->IsErrored())
02222 scanerror = -1;
02223
02224 ScanDSMCCStreams();
02225
02226 return scanerror;
02227 }
02228
02229 void AvFormatDecoder::UpdateFramesPlayed(void)
02230 {
02231 return DecoderBase::UpdateFramesPlayed();
02232 }
02233
02234 bool AvFormatDecoder::DoRewindSeek(long long desiredFrame)
02235 {
02236 return DecoderBase::DoRewindSeek(desiredFrame);
02237 }
02238
02239 void AvFormatDecoder::DoFastForwardSeek(long long desiredFrame, bool &needflush)
02240 {
02241 DecoderBase::DoFastForwardSeek(desiredFrame, needflush);
02242 return;
02243 }
02244
02246 int AvFormatDecoder::GetSubtitleLanguage(uint subtitle_index, uint stream_index)
02247 {
02248 (void)subtitle_index;
02249 AVDictionaryEntry *metatag =
02250 av_dict_get(ic->streams[stream_index]->metadata, "language", NULL, 0);
02251 return metatag ? get_canonical_lang(metatag->value) :
02252 iso639_str3_to_key("und");
02253 }
02254
02256 int AvFormatDecoder::GetCaptionLanguage(TrackTypes trackType, int service_num)
02257 {
02258 int ret = -1;
02259 for (uint i = 0; i < (uint) pmt_track_types.size(); i++)
02260 {
02261 if ((pmt_track_types[i] == trackType) &&
02262 (pmt_tracks[i].stream_id == service_num))
02263 {
02264 ret = pmt_tracks[i].language;
02265 if (!iso639_is_key_undefined(ret))
02266 return ret;
02267 }
02268 }
02269
02270 for (uint i = 0; i < (uint) stream_track_types.size(); i++)
02271 {
02272 if ((stream_track_types[i] == trackType) &&
02273 (stream_tracks[i].stream_id == service_num))
02274 {
02275 ret = stream_tracks[i].language;
02276 if (!iso639_is_key_undefined(ret))
02277 return ret;
02278 }
02279 }
02280
02281 return ret;
02282 }
02283
02284 int AvFormatDecoder::GetAudioLanguage(uint audio_index, uint stream_index)
02285 {
02286 return GetSubtitleLanguage(audio_index, stream_index);
02287 }
02288
02301 void AvFormatDecoder::SetupAudioStreamSubIndexes(int streamIndex)
02302 {
02303 QMutexLocker locker(avcodeclock);
02304
02305
02306 sinfo_vec_t::iterator current = tracks[kTrackTypeAudio].begin();
02307 for (; current != tracks[kTrackTypeAudio].end(); ++current)
02308 {
02309 if (current->av_stream_index == streamIndex)
02310 break;
02311 }
02312
02313 if (current == tracks[kTrackTypeAudio].end())
02314 {
02315 LOG(VB_GENERAL, LOG_WARNING, LOC +
02316 QString("Invalid stream index passed to "
02317 "SetupAudioStreamSubIndexes: %1").arg(streamIndex));
02318
02319 return;
02320 }
02321
02322
02323 sinfo_vec_t::iterator next = current + 1;
02324 if (current->av_substream_index == -1)
02325 {
02326
02327 StreamInfo lang1 = *current;
02328 StreamInfo lang2 = *current;
02329 lang1.av_substream_index = 0;
02330 lang2.av_substream_index = 1;
02331 *current = lang1;
02332 tracks[kTrackTypeAudio].insert(next, lang2);
02333 return;
02334 }
02335
02336 if ((next == tracks[kTrackTypeAudio].end()) ||
02337 (next->av_stream_index != streamIndex))
02338 {
02339 QString msg = QString(
02340 "Expected substream 1 (Language I) of stream %1\n\t\t\t"
02341 "following substream 0, found end of list or another stream.")
02342 .arg(streamIndex);
02343
02344 LOG(VB_GENERAL, LOG_WARNING, LOC + msg);
02345
02346 return;
02347 }
02348
02349
02350 StreamInfo stream = *current;
02351 stream.av_substream_index = -1;
02352 *current = stream;
02353 tracks[kTrackTypeAudio].erase(next);
02354 }
02355
02356 int get_avf_buffer(struct AVCodecContext *c, AVFrame *pic)
02357 {
02358 AvFormatDecoder *nd = (AvFormatDecoder *)(c->opaque);
02359
02360 if (!IS_DR1_PIX_FMT(c->pix_fmt))
02361 {
02362 nd->directrendering = false;
02363 return avcodec_default_get_buffer(c, pic);
02364 }
02365 nd->directrendering = true;
02366
02367 VideoFrame *frame = nd->GetPlayer()->GetNextVideoFrame();
02368
02369 if (!frame)
02370 return -1;
02371
02372 for (int i = 0; i < 3; i++)
02373 {
02374 pic->data[i] = frame->buf + frame->offsets[i];
02375 pic->linesize[i] = frame->pitches[i];
02376 }
02377
02378 pic->opaque = frame;
02379 pic->type = FF_BUFFER_TYPE_USER;
02380
02381 pic->reordered_opaque = c->reordered_opaque;
02382
02383 return 0;
02384 }
02385
02390 void AvFormatDecoder::RemoveAudioStreams()
02391 {
02392 if (!m_audio->HasAudioIn())
02393 return;
02394
02395 QMutexLocker locker(avcodeclock);
02396 for (uint i = 0; i < ic->nb_streams;)
02397 {
02398 AVStream *st = ic->streams[i];
02399 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
02400 {
02401 av_remove_stream(ic, st->id, 0);
02402 i--;
02403 }
02404 else
02405 i++;
02406 }
02407 }
02408
02409 void release_avf_buffer(struct AVCodecContext *c, AVFrame *pic)
02410 {
02411 (void)c;
02412
02413 if (pic->type == FF_BUFFER_TYPE_INTERNAL)
02414 {
02415 avcodec_default_release_buffer(c, pic);
02416 return;
02417 }
02418
02419 AvFormatDecoder *nd = (AvFormatDecoder *)(c->opaque);
02420 if (nd && nd->GetPlayer())
02421 nd->GetPlayer()->DeLimboFrame((VideoFrame*)pic->opaque);
02422
02423 assert(pic->type == FF_BUFFER_TYPE_USER);
02424
02425 for (uint i = 0; i < 4; i++)
02426 pic->data[i] = NULL;
02427 }
02428
02429 int get_avf_buffer_vdpau(struct AVCodecContext *c, AVFrame *pic)
02430 {
02431 AvFormatDecoder *nd = (AvFormatDecoder *)(c->opaque);
02432 VideoFrame *frame = nd->GetPlayer()->GetNextVideoFrame();
02433
02434 pic->data[0] = frame->buf;
02435 pic->data[1] = frame->priv[0];
02436 pic->data[2] = frame->priv[1];
02437
02438 pic->linesize[0] = 0;
02439 pic->linesize[1] = 0;
02440 pic->linesize[2] = 0;
02441
02442 pic->opaque = frame;
02443 pic->type = FF_BUFFER_TYPE_USER;
02444
02445 frame->pix_fmt = c->pix_fmt;
02446
02447 #ifdef USING_VDPAU
02448 struct vdpau_render_state *render = (struct vdpau_render_state *)frame->buf;
02449 render->state |= FF_VDPAU_STATE_USED_FOR_REFERENCE;
02450 #endif
02451
02452 pic->reordered_opaque = c->reordered_opaque;
02453
02454 return 0;
02455 }
02456
02457 void release_avf_buffer_vdpau(struct AVCodecContext *c, AVFrame *pic)
02458 {
02459 assert(pic->type == FF_BUFFER_TYPE_USER);
02460
02461 #ifdef USING_VDPAU
02462 struct vdpau_render_state *render = (struct vdpau_render_state *)pic->data[0];
02463 render->state &= ~FF_VDPAU_STATE_USED_FOR_REFERENCE;
02464 #endif
02465
02466 AvFormatDecoder *nd = (AvFormatDecoder *)(c->opaque);
02467 if (nd && nd->GetPlayer())
02468 nd->GetPlayer()->DeLimboFrame((VideoFrame*)pic->opaque);
02469
02470 for (uint i = 0; i < 4; i++)
02471 pic->data[i] = NULL;
02472 }
02473
02474 void render_slice_vdpau(struct AVCodecContext *s, const AVFrame *src,
02475 int offset[4], int y, int type, int height)
02476 {
02477 if (!src)
02478 return;
02479
02480 (void)offset;
02481 (void)type;
02482
02483 if (s && src && s->opaque && src->opaque)
02484 {
02485 AvFormatDecoder *nd = (AvFormatDecoder *)(s->opaque);
02486
02487 int width = s->width;
02488
02489 VideoFrame *frame = (VideoFrame *)src->opaque;
02490 nd->GetPlayer()->DrawSlice(frame, 0, y, width, height);
02491 }
02492 else
02493 {
02494 LOG(VB_GENERAL, LOG_ERR, LOC +
02495 "render_slice_vdpau called with bad avctx or src");
02496 }
02497 }
02498
02499 int get_avf_buffer_dxva2(struct AVCodecContext *c, AVFrame *pic)
02500 {
02501 AvFormatDecoder *nd = (AvFormatDecoder *)(c->opaque);
02502 VideoFrame *frame = nd->GetPlayer()->GetNextVideoFrame();
02503 for (int i = 0; i < 4; i++)
02504 {
02505 pic->data[i] = NULL;
02506 pic->linesize[i] = 0;
02507 }
02508 pic->reordered_opaque = c->reordered_opaque;
02509 pic->opaque = frame;
02510 pic->type = FF_BUFFER_TYPE_USER;
02511 frame->pix_fmt = c->pix_fmt;
02512
02513 #ifdef USING_DXVA2
02514 if (nd->GetPlayer())
02515 {
02516 static uint8_t *dummy[1] = { 0 };
02517 c->hwaccel_context =
02518 (dxva_context*)nd->GetPlayer()->GetDecoderContext(NULL, dummy[0]);
02519 pic->data[0] = (uint8_t*)frame->buf;
02520 pic->data[3] = (uint8_t*)frame->buf;
02521 }
02522 #endif
02523
02524 return 0;
02525 }
02526
02527 int get_avf_buffer_vaapi(struct AVCodecContext *c, AVFrame *pic)
02528 {
02529 AvFormatDecoder *nd = (AvFormatDecoder *)(c->opaque);
02530 VideoFrame *frame = nd->GetPlayer()->GetNextVideoFrame();
02531
02532 pic->data[0] = frame->buf;
02533 pic->data[1] = NULL;
02534 pic->data[2] = NULL;
02535 pic->data[3] = NULL;
02536 pic->linesize[0] = 0;
02537 pic->linesize[1] = 0;
02538 pic->linesize[2] = 0;
02539 pic->linesize[3] = 0;
02540 pic->opaque = frame;
02541 pic->type = FF_BUFFER_TYPE_USER;
02542 frame->pix_fmt = c->pix_fmt;
02543
02544 #ifdef USING_VAAPI
02545 if (nd->GetPlayer())
02546 c->hwaccel_context = (vaapi_context*)nd->GetPlayer()->GetDecoderContext(frame->buf, pic->data[3]);
02547 #endif
02548
02549 return 0;
02550 }
02551
02552 void AvFormatDecoder::DecodeDTVCC(const uint8_t *buf, uint len, bool scte)
02553 {
02554 if (!len)
02555 return;
02556
02557
02558
02559
02560
02561 bool process_cc_data = buf[0] & 0x40;
02562 if (!process_cc_data)
02563 return;
02564
02565
02566
02567
02568 uint cc_count = buf[0] & 0x1f;
02569
02570
02571 if (len < 2+(3*cc_count))
02572 return;
02573
02574 bool had_608 = false, had_708 = false;
02575 for (uint cur = 0; cur < cc_count; cur++)
02576 {
02577 uint cc_code = buf[2+(cur*3)];
02578 bool cc_valid = cc_code & 0x04;
02579
02580 uint data1 = buf[3+(cur*3)];
02581 uint data2 = buf[4+(cur*3)];
02582 uint data = (data2 << 8) | data1;
02583 uint cc_type = cc_code & 0x03;
02584 uint field;
02585
02586 if (!cc_valid)
02587 {
02588 if (cc_type >= 0x2)
02589 ccd708->decode_cc_null();
02590 continue;
02591 }
02592
02593 if (scte || cc_type <= 0x1)
02594 {
02595 if (cc_type == 0x2)
02596 {
02597
02598 field = !last_scte_field;
02599 invert_scte_field = !invert_scte_field;
02600 }
02601 else
02602 {
02603 field = cc_type ^ invert_scte_field;
02604 }
02605
02606 if (cc608_good_parity(cc608_parity_table, data))
02607 {
02608
02609
02610
02611 if (scte && field == 0 &&
02612 (data1 & 0x7f) <= 0x0f && (data1 & 0x7f) != 0x00)
02613 {
02614 if (cc_type == 1)
02615 invert_scte_field = 0;
02616 field = 1;
02617
02618
02619 ccd608->FormatCC(0, -1, -1);
02620 }
02621
02622 had_608 = true;
02623 ccd608->FormatCCField(lastccptsu / 1000, field, data);
02624
02625 last_scte_field = field;
02626 }
02627 }
02628 else
02629 {
02630 had_708 = true;
02631 ccd708->decode_cc_data(cc_type, data1, data2);
02632 }
02633 }
02634 UpdateCaptionTracksFromStreams(had_608, had_708);
02635 }
02636
02637 void AvFormatDecoder::UpdateCaptionTracksFromStreams(
02638 bool check_608, bool check_708)
02639 {
02640 bool need_change_608 = false;
02641 bool seen_608[4];
02642 if (check_608)
02643 {
02644 ccd608->GetServices(15, seen_608);
02645 for (uint i = 0; i < 4; i++)
02646 {
02647 need_change_608 |= (seen_608[i] && !ccX08_in_tracks[i]) ||
02648 (!seen_608[i] && ccX08_in_tracks[i] && !ccX08_in_pmt[i]);
02649 }
02650 }
02651
02652 bool need_change_708 = false;
02653 bool seen_708[64];
02654 if (check_708 || need_change_608)
02655 {
02656 ccd708->services(15, seen_708);
02657 for (uint i = 1; i < 64 && !need_change_608 && !need_change_708; i++)
02658 {
02659 need_change_708 |= (seen_708[i] && !ccX08_in_tracks[i+4]) ||
02660 (!seen_708[i] && ccX08_in_tracks[i+4] && !ccX08_in_pmt[i+4]);
02661 }
02662 if (need_change_708 && !check_608)
02663 ccd608->GetServices(15, seen_608);
02664 }
02665
02666 if (!need_change_608 && !need_change_708)
02667 return;
02668
02669 ScanATSCCaptionStreams(selectedTrack[kTrackTypeVideo].av_stream_index);
02670
02671 stream_tracks.clear();
02672 stream_track_types.clear();
02673 int av_index = selectedTrack[kTrackTypeVideo].av_stream_index;
02674 int lang = iso639_str3_to_key("und");
02675 for (uint i = 1; i < 64; i++)
02676 {
02677 if (seen_708[i] && !ccX08_in_pmt[i+4])
02678 {
02679 StreamInfo si(av_index, lang, 0,
02680 i, false, true);
02681 stream_tracks.push_back(si);
02682 stream_track_types.push_back(kTrackTypeCC708);
02683 }
02684 }
02685 for (uint i = 0; i < 4; i++)
02686 {
02687 if (seen_608[i] && !ccX08_in_pmt[i])
02688 {
02689 if (0==i)
02690 lang = GetCaptionLanguage(kTrackTypeCC708, 1);
02691 else if (2==i)
02692 lang = GetCaptionLanguage(kTrackTypeCC708, 2);
02693 else
02694 lang = iso639_str3_to_key("und");
02695
02696 StreamInfo si(av_index, lang, 0,
02697 i+1, false, false);
02698 stream_tracks.push_back(si);
02699 stream_track_types.push_back(kTrackTypeCC608);
02700 }
02701 }
02702 UpdateATSCCaptionTracks();
02703 }
02704
02705 void AvFormatDecoder::HandleGopStart(
02706 AVPacket *pkt, bool can_reliably_parse_keyframes)
02707 {
02708 if (prevgoppos != 0 && keyframedist != 1)
02709 {
02710 int tempKeyFrameDist = framesRead - 1 - prevgoppos;
02711 bool reset_kfd = false;
02712
02713 if (!gopset || livetv)
02714 {
02715 LOG(VB_PLAYBACK, LOG_INFO, LOC +
02716 "gopset not set, syncing positionMap");
02717 SyncPositionMap();
02718 if (tempKeyFrameDist > 0 && !livetv)
02719 {
02720 LOG(VB_PLAYBACK, LOG_INFO, LOC +
02721 QString("Initial key frame distance: %1.")
02722 .arg(keyframedist));
02723 gopset = true;
02724 reset_kfd = true;
02725 }
02726 }
02727 else if (keyframedist != tempKeyFrameDist && tempKeyFrameDist > 0)
02728 {
02729 LOG(VB_PLAYBACK, LOG_INFO, LOC +
02730 QString("Key frame distance changed from %1 to %2.")
02731 .arg(keyframedist).arg(tempKeyFrameDist));
02732 reset_kfd = true;
02733 }
02734
02735 if (reset_kfd)
02736 {
02737 keyframedist = tempKeyFrameDist;
02738 maxkeyframedist = max(keyframedist, maxkeyframedist);
02739
02740 m_parent->SetKeyframeDistance(keyframedist);
02741
02742 #if 0
02743
02744 QMutexLocker locker(&m_positionMapLock);
02745 if (!m_positionMap.empty())
02746 {
02747 long long index = m_positionMap.back().index;
02748 long long totframes = index * keyframedist;
02749 uint length = (uint)((totframes * 1.0f) / fps);
02750 m_parent->SetFileLength(length, totframes);
02751 }
02752 #endif
02753 }
02754 }
02755
02756 lastKey = prevgoppos = framesRead - 1;
02757
02758 if (can_reliably_parse_keyframes &&
02759 !hasFullPositionMap && !livetv && !watchingrecording)
02760 {
02761 long long last_frame = 0;
02762 {
02763 QMutexLocker locker(&m_positionMapLock);
02764 if (!m_positionMap.empty())
02765 last_frame = m_positionMap.back().index;
02766 }
02767
02768 #if 0
02769 LOG(VB_PLAYBACK, LOG_DEBUG, LOC +
02770 QString("framesRead: %1 last_frame: %2 keyframedist: %3")
02771 .arg(framesRead) .arg(last_frame) .arg(keyframedist));
02772 #endif
02773
02774
02775 if (framesRead > last_frame && keyframedist > 0)
02776 {
02777 long long startpos = pkt->pos;
02778
02779 LOG(VB_PLAYBACK | VB_TIMESTAMP, LOG_INFO, LOC +
02780 QString("positionMap[ %1 ] == %2.")
02781 .arg(framesRead).arg(startpos));
02782
02783 PosMapEntry entry = {framesRead, framesRead, startpos};
02784
02785 QMutexLocker locker(&m_positionMapLock);
02786 m_positionMap.push_back(entry);
02787 }
02788
02789 #if 0
02790
02791
02792 if (framesRead > 150 && !recordingHasPositionMap && !livetv)
02793 {
02794 bitrate = (int)((pkt->pos * 8 * fps) / (framesRead - 1));
02795 float bytespersec = (float)bitrate / 8;
02796 float secs = ringBuffer->GetRealFileSize() * 1.0 / bytespersec;
02797 m_parent->SetFileLength((int)(secs), (int)(secs * fps));
02798 }
02799 #endif
02800 }
02801 }
02802
02803 #define SEQ_START 0x000001b3
02804 #define GOP_START 0x000001b8
02805 #define PICTURE_START 0x00000100
02806 #define SLICE_MIN 0x00000101
02807 #define SLICE_MAX 0x000001af
02808 #define SEQ_END_CODE 0x000001b7
02809
02810 void AvFormatDecoder::MpegPreProcessPkt(AVStream *stream, AVPacket *pkt)
02811 {
02812 AVCodecContext *context = stream->codec;
02813 const uint8_t *bufptr = pkt->data;
02814 const uint8_t *bufend = pkt->data + pkt->size;
02815
02816 while (bufptr < bufend)
02817 {
02818 bufptr = avpriv_mpv_find_start_code(bufptr, bufend, &start_code_state);
02819
02820 float aspect_override = -1.0f;
02821 if (ringBuffer->IsDVD())
02822 {
02823 if (start_code_state == SEQ_END_CODE)
02824 ringBuffer->DVD()->NewSequence(true);
02825 aspect_override = ringBuffer->DVD()->GetAspectOverride();
02826 }
02827
02828 if (start_code_state >= SLICE_MIN && start_code_state <= SLICE_MAX)
02829 continue;
02830 else if (SEQ_START == start_code_state)
02831 {
02832 if (bufptr + 11 >= pkt->data + pkt->size)
02833 continue;
02834 SequenceHeader *seq = reinterpret_cast<SequenceHeader*>(
02835 const_cast<uint8_t*>(bufptr));
02836
02837 uint width = seq->width() >> context->lowres;
02838 uint height = seq->height() >> context->lowres;
02839 current_aspect = seq->aspect(context->codec_id ==
02840 CODEC_ID_MPEG1VIDEO);
02841 if (aspect_override > 0.0f)
02842 current_aspect = aspect_override;
02843 float seqFPS = seq->fps();
02844
02845 bool changed = (seqFPS > fps+0.01f) || (seqFPS < fps-0.01f);
02846 changed |= (width != (uint)current_width );
02847 changed |= (height != (uint)current_height);
02848
02849 if (changed)
02850 {
02851 m_parent->SetVideoParams(width, height, seqFPS, kScan_Detect);
02852
02853 current_width = width;
02854 current_height = height;
02855 fps = seqFPS;
02856
02857 if (private_dec)
02858 private_dec->Reset();
02859
02860 gopset = false;
02861 prevgoppos = 0;
02862 firstvpts = lastapts = lastvpts = lastccptsu = 0;
02863 firstvptsinuse = true;
02864 faulty_pts = faulty_dts = 0;
02865 last_pts_for_fault_detection = 0;
02866 last_dts_for_fault_detection = 0;
02867 pts_detected = false;
02868 reordered_pts_detected = false;
02869
02870
02871 float avFPS = normalized_fps(stream, context);
02872 if ((seqFPS > avFPS+0.01f) || (seqFPS < avFPS-0.01f))
02873 {
02874 LOG(VB_PLAYBACK, LOG_INFO, LOC +
02875 QString("avFPS(%1) != seqFPS(%2)")
02876 .arg(avFPS).arg(seqFPS));
02877 }
02878 }
02879
02880 seq_count++;
02881
02882 if (!seen_gop && seq_count > 1)
02883 {
02884 HandleGopStart(pkt, true);
02885 pkt->flags |= AV_PKT_FLAG_KEY;
02886 }
02887 }
02888 else if (GOP_START == start_code_state)
02889 {
02890 HandleGopStart(pkt, true);
02891 seen_gop = true;
02892 pkt->flags |= AV_PKT_FLAG_KEY;
02893 }
02894 }
02895 }
02896
02897 bool AvFormatDecoder::H264PreProcessPkt(AVStream *stream, AVPacket *pkt)
02898 {
02899 AVCodecContext *context = stream->codec;
02900 const uint8_t *buf = pkt->data;
02901 const uint8_t *buf_end = pkt->data + pkt->size;
02902 bool on_frame = false;
02903
02904
02905
02906 if (context->extradata && context->extradata_size >= 4)
02907 {
02908 int nal_size = 0;
02909 int size_length = (context->extradata[4] & 0x3) + 1;
02910
02911 for (int i = 0; i < size_length; i++)
02912 nal_size += buf[i];
02913
02914 if (nal_size)
02915 {
02916 if (pkt->flags & AV_PKT_FLAG_KEY)
02917 HandleGopStart(pkt, false);
02918 return true;
02919 }
02920 }
02921
02922 while (buf < buf_end)
02923 {
02924 buf += m_h264_parser->addBytes(buf, buf_end - buf, 0);
02925
02926 if (m_h264_parser->stateChanged())
02927 {
02928 if (m_h264_parser->FieldType() != H264Parser::FIELD_BOTTOM)
02929 {
02930 if (m_h264_parser->onFrameStart())
02931 on_frame = true;
02932
02933 if (!m_h264_parser->onKeyFrameStart())
02934 continue;
02935 }
02936 else
02937 {
02938 continue;
02939 }
02940 }
02941 else
02942 {
02943 continue;
02944 }
02945
02946 current_aspect = get_aspect(*context);
02947 QSize dim = get_video_dim(*context);
02948 uint width = dim.width();
02949 uint height = dim.height();
02950 float seqFPS = normalized_fps(stream, context);
02951
02952 bool changed = (seqFPS > fps+0.01f) || (seqFPS < fps-0.01f);
02953 changed |= (width != (uint)current_width );
02954 changed |= (height != (uint)current_height);
02955
02956 if (changed)
02957 {
02958 m_parent->SetVideoParams(width, height, seqFPS, kScan_Detect);
02959
02960 current_width = width;
02961 current_height = height;
02962 fps = seqFPS;
02963
02964 gopset = false;
02965 prevgoppos = 0;
02966 firstvpts = lastapts = lastvpts = lastccptsu = 0;
02967 firstvptsinuse = true;
02968 faulty_pts = faulty_dts = 0;
02969 last_pts_for_fault_detection = 0;
02970 last_dts_for_fault_detection = 0;
02971 pts_detected = false;
02972 reordered_pts_detected = false;
02973
02974
02975 float avFPS = normalized_fps(stream, context);
02976 if ((seqFPS > avFPS+0.01f) || (seqFPS < avFPS-0.01f))
02977 {
02978 LOG(VB_PLAYBACK, LOG_INFO, LOC +
02979 QString("avFPS(%1) != seqFPS(%2)")
02980 .arg(avFPS).arg(seqFPS));
02981 }
02982 }
02983
02984 HandleGopStart(pkt, true);
02985 pkt->flags |= AV_PKT_FLAG_KEY;
02986 }
02987
02988 return on_frame;
02989 }
02990
02991 bool AvFormatDecoder::PreProcessVideoPacket(AVStream *curstream, AVPacket *pkt)
02992 {
02993 AVCodecContext *context = curstream->codec;
02994 bool on_frame = true;
02995
02996 if (CODEC_IS_FFMPEG_MPEG(context->codec_id))
02997 {
02998 MpegPreProcessPkt(curstream, pkt);
02999 }
03000 else if (CODEC_IS_H264(context->codec_id))
03001 {
03002 on_frame = H264PreProcessPkt(curstream, pkt);
03003 }
03004 else
03005 {
03006 if (pkt->flags & AV_PKT_FLAG_KEY)
03007 {
03008 HandleGopStart(pkt, false);
03009 seen_gop = true;
03010 }
03011 else
03012 {
03013 seq_count++;
03014 if (!seen_gop && seq_count > 1)
03015 {
03016 HandleGopStart(pkt, false);
03017 }
03018 }
03019 }
03020
03021 if (framesRead == 0 && !justAfterChange &&
03022 !(pkt->flags & AV_PKT_FLAG_KEY))
03023 {
03024 av_free_packet(pkt);
03025 return false;
03026 }
03027
03028 if (on_frame)
03029 framesRead++;
03030
03031 totalDuration += av_q2d(curstream->time_base) * pkt->duration * 1000000;
03032
03033 justAfterChange = false;
03034
03035 if (exitafterdecoded)
03036 gotVideoFrame = 1;
03037
03038 return true;
03039 }
03040
03041 bool AvFormatDecoder::ProcessVideoPacket(AVStream *curstream, AVPacket *pkt)
03042 {
03043 int ret = 0, gotpicture = 0;
03044 int64_t pts = 0;
03045 AVCodecContext *context = curstream->codec;
03046 AVFrame mpa_pic;
03047 avcodec_get_frame_defaults(&mpa_pic);
03048 mpa_pic.reordered_opaque = AV_NOPTS_VALUE;
03049
03050 if (pkt->pts != (int64_t)AV_NOPTS_VALUE)
03051 pts_detected = true;
03052
03053 avcodeclock->lock();
03054 if (private_dec)
03055 {
03056 if (QString(ic->iformat->name).contains("avi") || !pts_detected)
03057 pkt->pts = pkt->dts;
03058
03059
03060
03061 ret = private_dec->GetFrame(curstream, &mpa_pic, &gotpicture, pkt);
03062 }
03063 else
03064 {
03065 context->reordered_opaque = pkt->pts;
03066 ret = avcodec_decode_video2(context, &mpa_pic, &gotpicture, pkt);
03067
03068 if (ringBuffer->IsDVD() && ringBuffer->DVD()->NeedsStillFrame())
03069 ret = avcodec_decode_video2(context, &mpa_pic, &gotpicture, pkt);
03070 }
03071 avcodeclock->unlock();
03072
03073 if (ret < 0)
03074 {
03075 LOG(VB_GENERAL, LOG_ERR, LOC + "Unknown decoding error");
03076 return false;
03077 }
03078
03079 if (!gotpicture)
03080 {
03081 return true;
03082 }
03083
03084
03085 if (pkt->dts != (int64_t)AV_NOPTS_VALUE)
03086 {
03087 faulty_dts += (pkt->dts <= last_dts_for_fault_detection);
03088 last_dts_for_fault_detection = pkt->dts;
03089 }
03090 if (mpa_pic.reordered_opaque != (int64_t)AV_NOPTS_VALUE)
03091 {
03092 faulty_pts += (mpa_pic.reordered_opaque <= last_pts_for_fault_detection);
03093 last_pts_for_fault_detection = mpa_pic.reordered_opaque;
03094 reordered_pts_detected = true;
03095 }
03096
03097
03098
03099
03100
03101
03102
03103 if (force_dts_timestamps)
03104 {
03105 if (pkt->dts != (int64_t)AV_NOPTS_VALUE)
03106 pts = pkt->dts;
03107 pts_selected = false;
03108 }
03109 else if (ringBuffer->IsDVD())
03110 {
03111 if (pkt->dts != (int64_t)AV_NOPTS_VALUE)
03112 pts = pkt->dts;
03113 pts_selected = false;
03114 }
03115 else if (private_dec && private_dec->NeedsReorderedPTS() &&
03116 mpa_pic.reordered_opaque != (int64_t)AV_NOPTS_VALUE)
03117 {
03118 pts = mpa_pic.reordered_opaque;
03119 pts_selected = true;
03120 }
03121 else if (faulty_pts <= faulty_dts && reordered_pts_detected)
03122 {
03123 if (mpa_pic.reordered_opaque != (int64_t)AV_NOPTS_VALUE)
03124 pts = mpa_pic.reordered_opaque;
03125 pts_selected = true;
03126 }
03127 else if (pkt->dts != (int64_t)AV_NOPTS_VALUE)
03128 {
03129 pts = pkt->dts;
03130 pts_selected = false;
03131 }
03132
03133 LOG(VB_PLAYBACK | VB_TIMESTAMP, LOG_DEBUG, LOC +
03134 QString("video packet timestamps reordered %1 pts %2 dts %3 (%4)")
03135 .arg(mpa_pic.reordered_opaque).arg(pkt->pts).arg(pkt->dts)
03136 .arg((force_dts_timestamps) ? "dts forced" :
03137 (pts_selected) ? "reordered" : "dts"));
03138
03139 mpa_pic.reordered_opaque = pts;
03140
03141 ProcessVideoFrame(curstream, &mpa_pic);
03142
03143 return true;
03144 }
03145
03146 bool AvFormatDecoder::ProcessVideoFrame(AVStream *stream, AVFrame *mpa_pic)
03147 {
03148 AVCodecContext *context = stream->codec;
03149
03150 uint cc_len = (uint) max(mpa_pic->scte_cc_len,0);
03151 uint8_t *cc_buf = mpa_pic->scte_cc_buf;
03152 bool scte = true;
03153
03154
03155 if ((mpa_pic->atsc_cc_len > 0) || ignore_scte)
03156 {
03157 ignore_scte = true;
03158 cc_len = (uint) max(mpa_pic->atsc_cc_len, 0);
03159 cc_buf = mpa_pic->atsc_cc_buf;
03160 scte = false;
03161 }
03162
03163
03164 for (uint i = 0; i < cc_len; i += ((cc_buf[i] & 0x1f) * 3) + 2)
03165 DecodeDTVCC(cc_buf + i, cc_len - i, scte);
03166
03167 VideoFrame *picframe = (VideoFrame *)(mpa_pic->opaque);
03168
03169 if (FlagIsSet(kDecodeNoDecode))
03170 {
03171
03172
03173
03174 }
03175 else if (!directrendering)
03176 {
03177 AVPicture tmppicture;
03178
03179 VideoFrame *xf = picframe;
03180 picframe = m_parent->GetNextVideoFrame();
03181
03182 unsigned char *buf = picframe->buf;
03183 avpicture_fill(&tmppicture, buf, PIX_FMT_YUV420P, context->width,
03184 context->height);
03185 tmppicture.data[0] = buf + picframe->offsets[0];
03186 tmppicture.data[1] = buf + picframe->offsets[1];
03187 tmppicture.data[2] = buf + picframe->offsets[2];
03188 tmppicture.linesize[0] = picframe->pitches[0];
03189 tmppicture.linesize[1] = picframe->pitches[1];
03190 tmppicture.linesize[2] = picframe->pitches[2];
03191
03192 QSize dim = get_video_dim(*context);
03193 sws_ctx = sws_getCachedContext(sws_ctx, context->width,
03194 context->height, context->pix_fmt,
03195 context->width, context->height,
03196 PIX_FMT_YUV420P, SWS_FAST_BILINEAR,
03197 NULL, NULL, NULL);
03198 if (!sws_ctx)
03199 {
03200 LOG(VB_GENERAL, LOG_ERR, LOC + "Failed to allocate sws context");
03201 return false;
03202 }
03203 sws_scale(sws_ctx, mpa_pic->data, mpa_pic->linesize, 0, dim.height(),
03204 tmppicture.data, tmppicture.linesize);
03205
03206 if (xf)
03207 {
03208
03209
03210 xf->interlaced_frame = mpa_pic->interlaced_frame;
03211 xf->top_field_first = mpa_pic->top_field_first;
03212 xf->frameNumber = framesPlayed;
03213 xf->aspect = current_aspect;
03214 m_parent->DiscardVideoFrame(xf);
03215 }
03216 }
03217 else if (!picframe)
03218 {
03219 LOG(VB_GENERAL, LOG_ERR, LOC + "NULL videoframe - direct rendering not"
03220 "correctly initialized.");
03221 return false;
03222 }
03223
03224 long long pts = (long long)(av_q2d(stream->time_base) *
03225 mpa_pic->reordered_opaque * 1000);
03226
03227 long long temppts = pts;
03228
03229
03230
03231 if (!ringBuffer->IsDVD() &&
03232 temppts <= lastvpts &&
03233 (temppts + (1000 / fps) > lastvpts || temppts <= 0))
03234 {
03235 temppts = lastvpts;
03236 temppts += (long long)(1000 / fps);
03237
03238 temppts += (long long)(mpa_pic->repeat_pict * 500 / fps);
03239 }
03240
03241 LOG(VB_PLAYBACK | VB_TIMESTAMP, LOG_INFO, LOC +
03242 QString("video timecode %1 %2 %3 %4%5")
03243 .arg(mpa_pic->reordered_opaque).arg(pts).arg(temppts).arg(lastvpts)
03244 .arg((pts != temppts) ? " fixup" : ""));
03245
03246 picframe->interlaced_frame = mpa_pic->interlaced_frame;
03247 picframe->top_field_first = mpa_pic->top_field_first;
03248 picframe->repeat_pict = mpa_pic->repeat_pict;
03249 picframe->disp_timecode = NormalizeVideoTimecode(stream, temppts);
03250 picframe->frameNumber = framesPlayed;
03251 picframe->aspect = current_aspect;
03252 picframe->dummy = 0;
03253
03254 m_parent->ReleaseNextVideoFrame(picframe, temppts);
03255 if (private_dec)
03256 context->release_buffer(context, mpa_pic);
03257
03258 decoded_video_frame = picframe;
03259 gotVideoFrame = 1;
03260 framesPlayed++;
03261
03262 lastvpts = temppts;
03263 if (!firstvpts && firstvptsinuse)
03264 firstvpts = temppts;
03265
03266 return true;
03267 }
03268
03274 void AvFormatDecoder::ProcessVBIDataPacket(
03275 const AVStream *stream, const AVPacket *pkt)
03276 {
03277 (void) stream;
03278
03279 const uint8_t *buf = pkt->data;
03280 uint64_t linemask = 0;
03281 unsigned long long utc = lastccptsu;
03282
03283
03284
03285 if ((buf[0]=='t') && (buf[1]=='v') && (buf[2] == '0'))
03286 {
03288 memcpy(&linemask, buf + 3, 8);
03289 buf += 11;
03290 }
03291 else if ((buf[0]=='T') && (buf[1]=='V') && (buf[2] == '0'))
03292 {
03293 linemask = 0xffffffffffffffffLL;
03294 buf += 3;
03295 }
03296 else
03297 {
03298 LOG(VB_VBI, LOG_ERR, LOC + QString("Unknown VBI data stream '%1%2%3'")
03299 .arg(QChar(buf[0])).arg(QChar(buf[1])).arg(QChar(buf[2])));
03300 return;
03301 }
03302
03303 static const uint min_blank = 6;
03304 for (uint i = 0; i < 36; i++)
03305 {
03306 if (!((linemask >> i) & 0x1))
03307 continue;
03308
03309 const uint line = ((i < 18) ? i : i-18) + min_blank;
03310 const uint field = (i<18) ? 0 : 1;
03311 const uint id2 = *buf & 0xf;
03312 switch (id2)
03313 {
03314 case VBI_TYPE_TELETEXT:
03315
03316
03317
03318 if (tracks[kTrackTypeTeletextMenu].empty())
03319 {
03320 StreamInfo si(pkt->stream_index, 0, 0, 0, 0);
03321 tracks[kTrackTypeTeletextMenu].push_back(si);
03322 }
03323 ttd->Decode(buf+1, VBI_IVTV);
03324 break;
03325 case VBI_TYPE_CC:
03326
03327
03328 if (21 == line)
03329 {
03330 int data = (buf[2] << 8) | buf[1];
03331 if (cc608_good_parity(cc608_parity_table, data))
03332 ccd608->FormatCCField(utc/1000, field, data);
03333 utc += 33367;
03334 }
03335 break;
03336 case VBI_TYPE_VPS:
03337
03338 ccd608->DecodeVPS(buf+1);
03339 break;
03340 case VBI_TYPE_WSS:
03341
03342
03343 ccd608->DecodeWSS(buf+1);
03344 break;
03345 }
03346 buf += 43;
03347 }
03348 lastccptsu = utc;
03349 UpdateCaptionTracksFromStreams(true, false);
03350 }
03351
03356 void AvFormatDecoder::ProcessDVBDataPacket(
03357 const AVStream*, const AVPacket *pkt)
03358 {
03359 const uint8_t *buf = pkt->data;
03360 const uint8_t *buf_end = pkt->data + pkt->size;
03361
03362
03363 while (buf < buf_end)
03364 {
03365 if (*buf == 0x10)
03366 {
03367 buf++;
03368 }
03369 else if (*buf == 0x02)
03370 {
03371 buf += 4;
03372 if ((buf_end - buf) >= 42)
03373 ttd->Decode(buf, VBI_DVB);
03374 buf += 42;
03375 }
03376 else if (*buf == 0x03)
03377 {
03378 buf += 4;
03379 if ((buf_end - buf) >= 42)
03380 ttd->Decode(buf, VBI_DVB_SUBTITLE);
03381 buf += 42;
03382 }
03383 else if (*buf == 0xff)
03384 {
03385 buf += 3;
03386 }
03387 else
03388 {
03389 LOG(VB_VBI, LOG_ERR, LOC +
03390 QString("VBI: Unknown descriptor: %1").arg(*buf));
03391 buf += 46;
03392 }
03393 }
03394 }
03395
03399 void AvFormatDecoder::ProcessDSMCCPacket(
03400 const AVStream *str, const AVPacket *pkt)
03401 {
03402 #ifdef USING_MHEG
03403 if (!itv && ! (itv = m_parent->GetInteractiveTV()))
03404 return;
03405
03406
03407 uint8_t *data = pkt->data;
03408 int length = pkt->size;
03409 int componentTag, dataBroadcastId;
03410 unsigned carouselId;
03411 {
03412 QMutexLocker locker(avcodeclock);
03413 componentTag = str->component_tag;
03414 dataBroadcastId = str->codec->flags;
03415 carouselId = (unsigned) str->codec->sub_id;
03416 }
03417 while (length > 3)
03418 {
03419 uint16_t sectionLen = (((data[1] & 0xF) << 8) | data[2]) + 3;
03420
03421 if (sectionLen > length)
03422 return;
03423
03424 itv->ProcessDSMCCSection(data, sectionLen,
03425 componentTag, carouselId,
03426 dataBroadcastId);
03427 length -= sectionLen;
03428 data += sectionLen;
03429 }
03430 #endif // USING_MHEG
03431 }
03432
03433 bool AvFormatDecoder::ProcessSubtitlePacket(AVStream *curstream, AVPacket *pkt)
03434 {
03435 if (!m_parent->GetSubReader(pkt->stream_index))
03436 return true;
03437
03438 long long pts = 0;
03439
03440 if (pkt->dts != (int64_t)AV_NOPTS_VALUE)
03441 pts = (long long)(av_q2d(curstream->time_base) * pkt->dts * 1000);
03442
03443 avcodeclock->lock();
03444 int subIdx = selectedTrack[kTrackTypeSubtitle].av_stream_index;
03445 bool isForcedTrack = selectedTrack[kTrackTypeSubtitle].forced;
03446 avcodeclock->unlock();
03447
03448 int gotSubtitles = 0;
03449 AVSubtitle subtitle;
03450 memset(&subtitle, 0, sizeof(AVSubtitle));
03451
03452 if (ringBuffer->IsDVD())
03453 {
03454 if (ringBuffer->DVD()->NumMenuButtons() > 0)
03455 {
03456 ringBuffer->DVD()->GetMenuSPUPkt(pkt->data, pkt->size,
03457 curstream->id);
03458 }
03459 else
03460 {
03461 if (pkt->stream_index == subIdx)
03462 {
03463 QMutexLocker locker(avcodeclock);
03464 ringBuffer->DVD()->DecodeSubtitles(&subtitle, &gotSubtitles,
03465 pkt->data, pkt->size);
03466 }
03467 }
03468 }
03469 else if (decodeAllSubtitles || pkt->stream_index == subIdx)
03470 {
03471 QMutexLocker locker(avcodeclock);
03472 avcodec_decode_subtitle2(curstream->codec, &subtitle, &gotSubtitles,
03473 pkt);
03474 }
03475
03476 if (gotSubtitles)
03477 {
03478 if (isForcedTrack)
03479 subtitle.forced = true;
03480 subtitle.start_display_time += pts;
03481 subtitle.end_display_time += pts;
03482 LOG(VB_PLAYBACK | VB_TIMESTAMP, LOG_INFO, LOC +
03483 QString("subtl timecode %1 %2 %3 %4")
03484 .arg(pkt->pts).arg(pkt->dts)
03485 .arg(subtitle.start_display_time)
03486 .arg(subtitle.end_display_time));
03487
03488 bool forcedon = m_parent->GetSubReader(pkt->stream_index)->AddAVSubtitle(
03489 subtitle, curstream->codec->codec_id == CODEC_ID_XSUB,
03490 m_parent->GetAllowForcedSubtitles());
03491 m_parent->EnableForcedSubtitles(forcedon || isForcedTrack);
03492 }
03493
03494 return true;
03495 }
03496
03497 bool AvFormatDecoder::ProcessRawTextPacket(AVPacket *pkt)
03498 {
03499 if (!(decodeAllSubtitles ||
03500 selectedTrack[kTrackTypeRawText].av_stream_index == pkt->stream_index))
03501 {
03502 return false;
03503 }
03504
03505 if (!m_parent->GetSubReader(pkt->stream_index+0x2000))
03506 return false;
03507
03508 QTextCodec *codec = QTextCodec::codecForName("utf-8");
03509 QTextDecoder *dec = codec->makeDecoder();
03510 QString text = dec->toUnicode((const char*)pkt->data, pkt->size);
03511 QStringList list = text.split('\n', QString::SkipEmptyParts);
03512 delete dec;
03513
03514 m_parent->GetSubReader(pkt->stream_index+0x2000)->
03515 AddRawTextSubtitle(list, pkt->convergence_duration);
03516
03517 return true;
03518 }
03519
03520 bool AvFormatDecoder::ProcessDataPacket(AVStream *curstream, AVPacket *pkt,
03521 DecodeType decodetype)
03522 {
03523 enum CodecID codec_id = curstream->codec->codec_id;
03524
03525 switch (codec_id)
03526 {
03527 case CODEC_ID_MPEG2VBI:
03528 ProcessVBIDataPacket(curstream, pkt);
03529 break;
03530 case CODEC_ID_DVB_VBI:
03531 ProcessDVBDataPacket(curstream, pkt);
03532 break;
03533 case CODEC_ID_DSMCC_B:
03534 {
03535 ProcessDSMCCPacket(curstream, pkt);
03536 GenerateDummyVideoFrames();
03537
03538
03539 #ifdef USING_MHEG
03540 if (!(decodetype & kDecodeVideo))
03541 allowedquit |= (itv && itv->ImageHasChanged());
03542 #endif // USING_MHEG:
03543 break;
03544 }
03545 }
03546 return true;
03547 }
03548
03549 int AvFormatDecoder::SetTrack(uint type, int trackNo)
03550 {
03551 bool ret = DecoderBase::SetTrack(type, trackNo);
03552
03553 if (kTrackTypeAudio == type)
03554 {
03555 QString msg = SetupAudioStream() ? "" : "not ";
03556 LOG(VB_AUDIO, LOG_INFO, LOC + "Audio stream type "+msg+"changed.");
03557 }
03558
03559 return ret;
03560 }
03561
03562 QString AvFormatDecoder::GetTrackDesc(uint type, uint trackNo) const
03563 {
03564 if (trackNo >= tracks[type].size())
03565 return "";
03566
03567 bool forced = tracks[type][trackNo].forced;
03568 int lang_key = tracks[type][trackNo].language;
03569 if (kTrackTypeAudio == type)
03570 {
03571 if (ringBuffer->IsDVD())
03572 lang_key = ringBuffer->DVD()->GetAudioLanguage(trackNo);
03573
03574 QString msg = iso639_key_toName(lang_key);
03575
03576 switch (tracks[type][trackNo].audio_type)
03577 {
03578 case kAudioTypeAudioDescription :
03579 msg += QObject::tr(" (Audio Description)",
03580 "Audio described for the visually impaired");
03581 break;
03582 case kAudioTypeCommentary :
03583 msg += QObject::tr(" (Commentary)", "Audio commentary track");
03584 break;
03585 case kAudioTypeNormal : default :
03586 int av_index = tracks[kTrackTypeAudio][trackNo].av_stream_index;
03587 AVStream *s = ic->streams[av_index];
03588
03589 if (s)
03590 {
03591 if (s->codec->codec_id == CODEC_ID_MP3)
03592 msg += QString(" MP%1").arg(s->codec->sub_id);
03593 else if (s->codec->codec)
03594 msg += QString(" %1").arg(s->codec->codec->name).toUpper();
03595
03596 int channels = 0;
03597 if (ringBuffer->IsDVD())
03598 channels = ringBuffer->DVD()->GetNumAudioChannels(trackNo);
03599 else if (s->codec->channels)
03600 channels = tracks[kTrackTypeAudio][trackNo].orig_num_channels;
03601
03602 if (channels == 0)
03603 msg += QString(" ?ch");
03604 else if((channels > 4) && !(channels & 1))
03605 msg += QString(" %1.1ch").arg(channels - 1);
03606 else
03607 msg += QString(" %1ch").arg(channels);
03608 }
03609
03610 break;
03611 }
03612
03613 return QString("%1: %2").arg(trackNo + 1).arg(msg);
03614 }
03615 else if (kTrackTypeSubtitle == type)
03616 {
03617 if (ringBuffer->IsDVD())
03618 lang_key = ringBuffer->DVD()->GetSubtitleLanguage(trackNo);
03619
03620 return QObject::tr("Subtitle") + QString(" %1: %2%3")
03621 .arg(trackNo + 1).arg(iso639_key_toName(lang_key))
03622 .arg(forced ? QObject::tr(" (forced)") : "");
03623 }
03624 else
03625 {
03626 return DecoderBase::GetTrackDesc(type, trackNo);
03627 }
03628 }
03629
03630 int AvFormatDecoder::GetTeletextDecoderType(void) const
03631 {
03632 return ttd->GetDecoderType();
03633 }
03634
03635 QString AvFormatDecoder::GetXDS(const QString &key) const
03636 {
03637 return ccd608->GetXDS(key);
03638 }
03639
03640 QByteArray AvFormatDecoder::GetSubHeader(uint trackNo) const
03641 {
03642 if (trackNo >= tracks[kTrackTypeSubtitle].size())
03643 return QByteArray();
03644
03645 int index = tracks[kTrackTypeSubtitle][trackNo].av_stream_index;
03646 if (!ic->streams[index]->codec)
03647 return QByteArray();
03648
03649 return QByteArray((char *)ic->streams[index]->codec->subtitle_header,
03650 ic->streams[index]->codec->subtitle_header_size);
03651 }
03652
03653 void AvFormatDecoder::GetAttachmentData(uint trackNo, QByteArray &filename,
03654 QByteArray &data)
03655 {
03656 if (trackNo >= tracks[kTrackTypeAttachment].size())
03657 return;
03658
03659 int index = tracks[kTrackTypeAttachment][trackNo].av_stream_index;
03660 AVDictionaryEntry *tag = av_dict_get(ic->streams[index]->metadata,
03661 "filename", NULL, 0);
03662 if (tag)
03663 filename = QByteArray(tag->value);
03664 data = QByteArray((char *)ic->streams[index]->codec->extradata,
03665 ic->streams[index]->codec->extradata_size);
03666 }
03667
03668 bool AvFormatDecoder::SetAudioByComponentTag(int tag)
03669 {
03670 for (uint i = 0; i < tracks[kTrackTypeAudio].size(); i++)
03671 {
03672 AVStream *s = ic->streams[tracks[kTrackTypeAudio][i].av_stream_index];
03673 if (s)
03674 {
03675 if ((s->component_tag == tag) ||
03676 ((tag <= 0) && s->component_tag <= 0))
03677 {
03678 return SetTrack(kTrackTypeAudio, i);
03679 }
03680 }
03681 }
03682 return false;
03683 }
03684
03685 bool AvFormatDecoder::SetVideoByComponentTag(int tag)
03686 {
03687 for (uint i = 0; i < ic->nb_streams; i++)
03688 {
03689 AVStream *s = ic->streams[i];
03690 if (s)
03691 {
03692 if (s->component_tag == tag)
03693 {
03694 StreamInfo si(i, 0, 0, 0, 0);
03695 selectedTrack[kTrackTypeVideo] = si;
03696 return true;
03697 }
03698 }
03699 }
03700 return false;
03701 }
03702
03703
03704 int AvFormatDecoder::AutoSelectTrack(uint type)
03705 {
03706 if (kTrackTypeAudio == type)
03707 return AutoSelectAudioTrack();
03708
03709 if (ringBuffer->IsInDiscMenuOrStillFrame())
03710 return -1;
03711
03712 return DecoderBase::AutoSelectTrack(type);
03713 }
03714
03715 static vector<int> filter_lang(const sinfo_vec_t &tracks, int lang_key)
03716 {
03717 vector<int> ret;
03718
03719 for (uint i = 0; i < tracks.size(); i++)
03720 if ((lang_key < 0) || tracks[i].language == lang_key)
03721 ret.push_back(i);
03722
03723 return ret;
03724 }
03725
03726 static sinfo_vec_t filter_type(const sinfo_vec_t &tracks, AudioTrackType type)
03727 {
03728 sinfo_vec_t ret;
03729
03730 for (uint i = 0; i < tracks.size(); i++)
03731 {
03732 if (tracks[i].audio_type == type)
03733 ret.push_back(tracks[i]);
03734 }
03735
03736 return ret;
03737 }
03738
03739 int AvFormatDecoder::filter_max_ch(const AVFormatContext *ic,
03740 const sinfo_vec_t &tracks,
03741 const vector<int> &fs,
03742 enum CodecID codecId,
03743 int profile)
03744 {
03745 int selectedTrack = -1, max_seen = -1;
03746
03747 vector<int>::const_iterator it = fs.begin();
03748 for (; it != fs.end(); ++it)
03749 {
03750 const int stream_index = tracks[*it].av_stream_index;
03751 const AVCodecContext *ctx = ic->streams[stream_index]->codec;
03752 if ((codecId == CODEC_ID_NONE || codecId == ctx->codec_id) &&
03753 (max_seen < ctx->channels))
03754 {
03755 if (codecId == CODEC_ID_DTS && profile > 0)
03756 {
03757
03758 if (!DoPassThrough(ctx, true) || ctx->profile != profile)
03759 continue;
03760 }
03761 selectedTrack = *it;
03762 max_seen = ctx->channels;
03763 }
03764 }
03765
03766 return selectedTrack;
03767 }
03768
03815 int AvFormatDecoder::AutoSelectAudioTrack(void)
03816 {
03817 const sinfo_vec_t &atracks = tracks[kTrackTypeAudio];
03818 StreamInfo &wtrack = wantedTrack[kTrackTypeAudio];
03819 StreamInfo &strack = selectedTrack[kTrackTypeAudio];
03820 int &ctrack = currentTrack[kTrackTypeAudio];
03821
03822 uint numStreams = atracks.size();
03823 if ((ctrack >= 0) && (ctrack < (int)numStreams))
03824 return ctrack;
03825
03826 #if 0
03827
03828 for (uint i = 0; i < atracks.size(); i++)
03829 {
03830 int idx = atracks[i].av_stream_index;
03831 AVCodecContext *codec_ctx = ic->streams[idx]->codec;
03832 AudioInfo item(codec_ctx->codec_id, codec_ctx->bps,
03833 codec_ctx->sample_rate, codec_ctx->channels,
03834 DoPassThrough(codec_ctx, true));
03835 LOG(VB_AUDIO, LOG_DEBUG, LOC + " * " + item.toString());
03836 }
03837 #endif
03838
03839 int selTrack = (1 == numStreams) ? 0 : -1;
03840 int wlang = wtrack.language;
03841
03842 if (selTrack < 0 && numStreams)
03843 {
03844 LOG(VB_AUDIO, LOG_INFO, LOC + "Trying to select default track");
03845 for (uint i = 0; i < atracks.size(); i++) {
03846 int idx = atracks[i].av_stream_index;
03847 if (ic->streams[idx]->disposition & AV_DISPOSITION_DEFAULT)
03848 {
03849 selTrack = i;
03850 break;
03851 }
03852 }
03853 }
03854
03855 if ((selTrack < 0) && (wtrack.av_substream_index >= 0))
03856 {
03857 LOG(VB_AUDIO, LOG_INFO, LOC + "Trying to reselect audio sub-stream");
03858
03859
03860
03861 int substream_index = wtrack.av_substream_index;
03862
03863 for (uint i = 0; i < numStreams; i++)
03864 {
03865 if (atracks[i].av_substream_index == substream_index)
03866 {
03867 selTrack = i;
03868 break;
03869 }
03870 }
03871 }
03872
03873 if ((selTrack < 0) && wlang >= -1 && numStreams)
03874 {
03875 LOG(VB_AUDIO, LOG_INFO, LOC + "Trying to reselect audio track");
03876
03877
03878
03879 uint windx = wtrack.language_index;
03880 for (uint i = 0; i < numStreams; i++)
03881 {
03882 if (wlang == atracks[i].language)
03883 {
03884 selTrack = i;
03885
03886 if (windx == atracks[i].language_index)
03887 break;
03888 }
03889 }
03890 }
03891
03892 if (selTrack < 0 && numStreams)
03893 {
03894 LOG(VB_AUDIO, LOG_INFO, LOC + "Trying to select audio track (w/lang)");
03895
03896
03897 sinfo_vec_t ftracks = filter_type(atracks, kAudioTypeNormal);
03898
03899 if (ftracks.empty())
03900 {
03901 LOG(VB_AUDIO, LOG_WARNING, "No audio tracks matched the filter so trying without filter.");
03902 ftracks = atracks;
03903 }
03904
03905
03906 QString language_key_convert = iso639_str2_to_str3(gCoreContext->GetLanguage());
03907 uint language_key = iso639_str3_to_key(language_key_convert);
03908 uint canonical_key = iso639_key_to_canonical_key(language_key);
03909
03910 vector<int> flang = filter_lang(ftracks, canonical_key);
03911
03912 if (m_audio->CanDTSHD())
03913 selTrack = filter_max_ch(ic, ftracks, flang, CODEC_ID_DTS,
03914 FF_PROFILE_DTS_HD_MA);
03915 if (selTrack < 0)
03916 selTrack = filter_max_ch(ic, ftracks, flang, CODEC_ID_TRUEHD);
03917
03918 if (selTrack < 0 && m_audio->CanDTSHD())
03919 selTrack = filter_max_ch(ic, ftracks, flang, CODEC_ID_DTS,
03920 FF_PROFILE_DTS_HD_HRA);
03921 if (selTrack < 0)
03922 selTrack = filter_max_ch(ic, ftracks, flang, CODEC_ID_EAC3);
03923
03924 if (selTrack < 0)
03925 selTrack = filter_max_ch(ic, ftracks, flang, CODEC_ID_DTS);
03926
03927 if (selTrack < 0)
03928 selTrack = filter_max_ch(ic, ftracks, flang, CODEC_ID_AC3);
03929
03930 if (selTrack < 0)
03931 selTrack = filter_max_ch(ic, ftracks, flang);
03932
03933
03934
03935 if (selTrack < 0)
03936 {
03937 vector<int>::const_iterator it = languagePreference.begin();
03938 for (; it != languagePreference.end() && selTrack < 0; ++it)
03939 {
03940 vector<int> flang = filter_lang(ftracks, *it);
03941
03942 if (m_audio->CanDTSHD())
03943 selTrack = filter_max_ch(ic, ftracks, flang, CODEC_ID_DTS,
03944 FF_PROFILE_DTS_HD_MA);
03945 if (selTrack < 0)
03946 selTrack = filter_max_ch(ic, ftracks, flang,
03947 CODEC_ID_TRUEHD);
03948
03949 if (selTrack < 0 && m_audio->CanDTSHD())
03950 selTrack = filter_max_ch(ic, ftracks, flang, CODEC_ID_DTS,
03951 FF_PROFILE_DTS_HD_HRA);
03952
03953 if (selTrack < 0)
03954 selTrack = filter_max_ch(ic, ftracks, flang,
03955 CODEC_ID_EAC3);
03956
03957 if (selTrack < 0)
03958 selTrack = filter_max_ch(ic, ftracks, flang, CODEC_ID_DTS);
03959
03960 if (selTrack < 0)
03961 selTrack = filter_max_ch(ic, ftracks, flang, CODEC_ID_AC3);
03962
03963 if (selTrack < 0)
03964 selTrack = filter_max_ch(ic, ftracks, flang);
03965 }
03966 }
03967
03968 if (selTrack < 0)
03969 {
03970 LOG(VB_AUDIO, LOG_INFO, LOC +
03971 "Trying to select audio track (wo/lang)");
03972 vector<int> flang = filter_lang(ftracks, -1);
03973
03974 if (m_audio->CanDTSHD())
03975 selTrack = filter_max_ch(ic, ftracks, flang, CODEC_ID_DTS,
03976 FF_PROFILE_DTS_HD_MA);
03977 if (selTrack < 0)
03978 selTrack = filter_max_ch(ic, ftracks, flang, CODEC_ID_TRUEHD);
03979
03980 if (selTrack < 0 && m_audio->CanDTSHD())
03981 selTrack = filter_max_ch(ic, ftracks, flang, CODEC_ID_DTS,
03982 FF_PROFILE_DTS_HD_HRA);
03983
03984 if (selTrack < 0)
03985 selTrack = filter_max_ch(ic, ftracks, flang, CODEC_ID_EAC3);
03986
03987 if (selTrack < 0)
03988 selTrack = filter_max_ch(ic, ftracks, flang, CODEC_ID_DTS);
03989
03990 if (selTrack < 0)
03991 selTrack = filter_max_ch(ic, ftracks, flang, CODEC_ID_AC3);
03992
03993 if (selTrack < 0)
03994 selTrack = filter_max_ch(ic, ftracks, flang);
03995 }
03996 }
03997
03998 if (selTrack < 0)
03999 {
04000 strack.av_stream_index = -1;
04001 if (ctrack != selTrack)
04002 {
04003 LOG(VB_AUDIO, LOG_INFO, LOC + "No suitable audio track exists.");
04004 ctrack = selTrack;
04005 }
04006 }
04007 else
04008 {
04009 ctrack = selTrack;
04010 strack = atracks[selTrack];
04011
04012 if (wtrack.av_stream_index < 0)
04013 wtrack = strack;
04014
04015 LOG(VB_AUDIO, LOG_INFO, LOC +
04016 QString("Selected track %1 (A/V Stream #%2)")
04017 .arg(GetTrackDesc(kTrackTypeAudio, ctrack))
04018 .arg(strack.av_stream_index));
04019 }
04020
04021 SetupAudioStream();
04022 return selTrack;
04023 }
04024
04025 static void extract_mono_channel(uint channel, AudioInfo *audioInfo,
04026 char *buffer, int bufsize)
04027 {
04028
04029 if (audioInfo->channels != 2)
04030 return;
04031
04032 if (channel >= (uint)audioInfo->channels)
04033 return;
04034
04035 const uint samplesize = audioInfo->sample_size;
04036 const uint samples = bufsize / samplesize;
04037 const uint halfsample = samplesize >> 1;
04038
04039 const char *from = (channel == 1) ? buffer + halfsample : buffer;
04040 char *to = (channel == 0) ? buffer + halfsample : buffer;
04041
04042 for (uint sample = 0; sample < samples;
04043 (sample++), (from += samplesize), (to += samplesize))
04044 {
04045 memmove(to, from, halfsample);
04046 }
04047 }
04048
04049 bool AvFormatDecoder::ProcessAudioPacket(AVStream *curstream, AVPacket *pkt,
04050 DecodeType decodetype)
04051 {
04052 AVCodecContext *ctx = curstream->codec;
04053 int ret = 0;
04054 int data_size = 0;
04055 bool firstloop = true;
04056 int decoded_size = -1;
04057
04058 avcodeclock->lock();
04059 int audIdx = selectedTrack[kTrackTypeAudio].av_stream_index;
04060 int audSubIdx = selectedTrack[kTrackTypeAudio].av_substream_index;
04061 avcodeclock->unlock();
04062
04063 AVPacket tmp_pkt;
04064 av_init_packet(&tmp_pkt);
04065 tmp_pkt.data = pkt->data;
04066 tmp_pkt.size = pkt->size;
04067
04068 while (tmp_pkt.size > 0)
04069 {
04070 bool reselectAudioTrack = false;
04071
04073 if (!m_audio->HasAudioIn())
04074 {
04075 LOG(VB_AUDIO, LOG_INFO, LOC +
04076 "Audio is disabled - trying to restart it");
04077 reselectAudioTrack = true;
04078 }
04080
04081
04082 bool wasDual = audSubIdx != -1;
04083 bool isDual = ctx->avcodec_dual_language;
04084 if ((wasDual && !isDual) || (!wasDual && isDual))
04085 {
04086 SetupAudioStreamSubIndexes(audIdx);
04087 reselectAudioTrack = true;
04088 }
04089
04090
04091
04092 bool already_decoded = false;
04093 if (!ctx->channels)
04094 {
04095 LOG(VB_GENERAL, LOG_INFO, LOC + QString("Setting channels to %1")
04096 .arg(audioOut.channels));
04097
04098 QMutexLocker locker(avcodeclock);
04099
04100 if (DoPassThrough(ctx, false) || !DecoderWillDownmix(ctx))
04101 {
04102
04103
04104
04105 ctx->request_channels = 0;
04106 }
04107 else
04108 {
04109 ctx->request_channels = m_audio->GetMaxChannels();
04110 if (ctx->codec_id == CODEC_ID_AC3)
04111 ctx->channels = m_audio->GetMaxChannels();
04112 }
04113
04114 ret = DecodeAudio(ctx, audioSamples, data_size, &tmp_pkt);
04115 decoded_size = data_size;
04116 already_decoded = true;
04117 reselectAudioTrack |= ctx->channels;
04118 }
04119
04120 if (reselectAudioTrack)
04121 {
04122 QMutexLocker locker(avcodeclock);
04123 currentTrack[kTrackTypeAudio] = -1;
04124 selectedTrack[kTrackTypeAudio].av_stream_index = -1;
04125 audIdx = -1;
04126 audSubIdx = -1;
04127 AutoSelectAudioTrack();
04128 audIdx = selectedTrack[kTrackTypeAudio].av_stream_index;
04129 audSubIdx = selectedTrack[kTrackTypeAudio].av_substream_index;
04130 }
04131
04132 if (!(decodetype & kDecodeAudio) || (pkt->stream_index != audIdx))
04133 break;
04134
04135 if (firstloop && pkt->pts != (int64_t)AV_NOPTS_VALUE)
04136 lastapts = (long long)(av_q2d(curstream->time_base) * pkt->pts * 1000);
04137
04138 if (skipaudio && selectedTrack[kTrackTypeVideo].av_stream_index > -1)
04139 {
04140 if ((lastapts < lastvpts - (10.0 / fps)) || lastvpts == 0)
04141 break;
04142 else
04143 skipaudio = false;
04144 }
04145
04146
04147 if (firstvptsinuse && firstvpts && (lastapts < firstvpts))
04148 {
04149 LOG(VB_PLAYBACK | VB_TIMESTAMP, LOG_INFO, LOC +
04150 QString("discarding early audio timecode %1 %2 %3")
04151 .arg(pkt->pts).arg(pkt->dts).arg(lastapts));
04152 break;
04153 }
04154 firstvptsinuse = false;
04155
04156 avcodeclock->lock();
04157 data_size = 0;
04158
04159 if (audioOut.do_passthru)
04160 {
04161 if (!already_decoded)
04162 {
04163 if (m_audio->NeedDecodingBeforePassthrough())
04164 {
04165 ret = DecodeAudio(ctx, audioSamples, data_size, &tmp_pkt);
04166 decoded_size = data_size;
04167 }
04168 else
04169 decoded_size = -1;
04170 }
04171 memcpy(audioSamples, tmp_pkt.data, tmp_pkt.size);
04172 data_size = tmp_pkt.size;
04173
04174 tmp_pkt.size = 0;
04175 }
04176 else
04177 {
04178 if (!already_decoded)
04179 {
04180 if (DecoderWillDownmix(ctx))
04181 {
04182 ctx->request_channels = m_audio->GetMaxChannels();
04183 if (ctx->codec_id == CODEC_ID_AC3)
04184 ctx->channels = m_audio->GetMaxChannels();
04185 }
04186 else
04187 ctx->request_channels = 0;
04188
04189 ret = DecodeAudio(ctx, audioSamples, data_size, &tmp_pkt);
04190 decoded_size = data_size;
04191 }
04192
04193
04194
04195 if (ctx->sample_rate != audioOut.sample_rate ||
04196 ctx->channels != audioOut.channels)
04197 {
04198 LOG(VB_GENERAL, LOG_INFO, LOC + "Audio stream changed");
04199 currentTrack[kTrackTypeAudio] = -1;
04200 selectedTrack[kTrackTypeAudio].av_stream_index = -1;
04201 audIdx = -1;
04202 AutoSelectAudioTrack();
04203 data_size = 0;
04204 }
04205 }
04206 avcodeclock->unlock();
04207
04208 if (ret < 0)
04209 {
04210 LOG(VB_GENERAL, LOG_ERR, LOC + "Unknown audio decoding error");
04211 return false;
04212 }
04213
04214 if (data_size <= 0)
04215 {
04216 tmp_pkt.data += ret;
04217 tmp_pkt.size -= ret;
04218 continue;
04219 }
04220
04221 long long temppts = lastapts;
04222
04223 if (audSubIdx != -1 && !audioOut.do_passthru)
04224 extract_mono_channel(audSubIdx, &audioOut,
04225 (char *)audioSamples, data_size);
04226
04227 int frames = (ctx->channels <= 0 || decoded_size < 0) ? -1 :
04228 decoded_size / (ctx->channels *
04229 av_get_bytes_per_sample(ctx->sample_fmt));
04230 m_audio->AddAudioData((char *)audioSamples, data_size, temppts, frames);
04231 if (audioOut.do_passthru && !m_audio->NeedDecodingBeforePassthrough())
04232 {
04233 lastapts += m_audio->LengthLastData();
04234 }
04235 else
04236 {
04237 lastapts += (long long)
04238 ((double)(frames * 1000) / ctx->sample_rate);
04239 }
04240
04241 LOG(VB_TIMESTAMP, LOG_INFO, LOC + QString("audio timecode %1 %2 %3 %4")
04242 .arg(pkt->pts).arg(pkt->dts).arg(temppts).arg(lastapts));
04243
04244 allowedquit |= ringBuffer->IsInDiscMenuOrStillFrame() ||
04245 m_audio->IsBufferAlmostFull();
04246
04247 tmp_pkt.data += ret;
04248 tmp_pkt.size -= ret;
04249 firstloop = false;
04250 }
04251
04252 return true;
04253 }
04254
04255 int AvFormatDecoder::DecodeAudio(AVCodecContext *ctx,
04256 uint8_t *buffer, int &data_size,
04257 AVPacket *pkt)
04258 {
04259 AVFrame frame;
04260 int got_frame = 0;
04261
04262 int ret = avcodec_decode_audio4(ctx, &frame, &got_frame, pkt);
04263 if (ret < 0 || !got_frame)
04264 {
04265 data_size = 0;
04266 return ret;
04267 }
04268
04269 int plane_size;
04270 int planar = av_sample_fmt_is_planar(ctx->sample_fmt);
04271 data_size = av_samples_get_buffer_size(&plane_size, ctx->channels,
04272 frame.nb_samples,
04273 ctx->sample_fmt, 1);
04274 memcpy(buffer, frame.extended_data[0], plane_size);
04275
04276 if (planar && ctx->channels > 1)
04277 {
04278 uint8_t *out = buffer + plane_size;
04279 for (int i = 1; i < ctx->channels; i++)
04280 {
04281 memcpy(out, frame.extended_data[i], plane_size);
04282 out += plane_size;
04283 }
04284 }
04285 return ret;
04286 }
04287
04288
04289 bool AvFormatDecoder::GetFrame(DecodeType decodetype)
04290 {
04291 AVPacket *pkt = NULL;
04292 bool have_err = false;
04293
04294 gotVideoFrame = false;
04295
04296 frame_decoded = 0;
04297 decoded_video_frame = NULL;
04298
04299 allowedquit = false;
04300 bool storevideoframes = false;
04301
04302 avcodeclock->lock();
04303 AutoSelectTracks();
04304 avcodeclock->unlock();
04305
04306 skipaudio = (lastvpts == 0);
04307
04308 hasVideo = HasVideo(ic);
04309 needDummyVideoFrames = false;
04310
04311 if (!hasVideo && (decodetype & kDecodeVideo))
04312 {
04313
04314
04315 needDummyVideoFrames = true;
04316 decodetype = (DecodeType)((int)decodetype & ~kDecodeVideo);
04317 skipaudio = false;
04318 }
04319
04320 allowedquit = m_audio->IsBufferAlmostFull();
04321
04322 if (private_dec && private_dec->HasBufferedFrames() &&
04323 (selectedTrack[kTrackTypeVideo].av_stream_index > -1))
04324 {
04325 AVStream *stream = ic->streams[selectedTrack[kTrackTypeVideo]
04326 .av_stream_index];
04327 AVFrame mpa_pic;
04328 avcodec_get_frame_defaults(&mpa_pic);
04329 int got_picture = 0;
04330 private_dec->GetFrame(stream, &mpa_pic, &got_picture, NULL);
04331 if (got_picture)
04332 ProcessVideoFrame(stream, &mpa_pic);
04333 }
04334
04335 while (!allowedquit)
04336 {
04337 if ((decodetype & kDecodeAudio) &&
04338 ((currentTrack[kTrackTypeAudio] < 0) ||
04339 (selectedTrack[kTrackTypeAudio].av_stream_index < 0)))
04340 {
04341
04342
04343 if (hasVideo)
04344 decodetype = (DecodeType)((int)decodetype & ~kDecodeAudio);
04345 else
04346 allowedquit = true;
04347 }
04348
04349 StreamChangeCheck();
04350
04351 if (gotVideoFrame)
04352 {
04353 if (decodetype == kDecodeNothing)
04354 {
04355
04356
04357 allowedquit = true;
04358 continue;
04359 }
04360 else if (lowbuffers && ((decodetype & kDecodeAV) == kDecodeAV) &&
04361 storedPackets.count() < max_video_queue_size &&
04362 lastapts < lastvpts + 100 &&
04363 !ringBuffer->IsInDiscMenuOrStillFrame())
04364 {
04365 storevideoframes = true;
04366 }
04367 else if (decodetype & kDecodeVideo)
04368 {
04369 if (storedPackets.count() >= max_video_queue_size)
04370 LOG(VB_GENERAL, LOG_WARNING, LOC +
04371 QString("Audio %1 ms behind video but already %2 "
04372 "video frames queued. AV-Sync might be broken.")
04373 .arg(lastvpts-lastapts).arg(storedPackets.count()));
04374 allowedquit = true;
04375 continue;
04376 }
04377 }
04378
04379 if (!storevideoframes && storedPackets.count() > 0)
04380 {
04381 if (pkt)
04382 {
04383 av_free_packet(pkt);
04384 delete pkt;
04385 }
04386 pkt = storedPackets.takeFirst();
04387 }
04388 else
04389 {
04390 if (!pkt)
04391 {
04392 pkt = new AVPacket;
04393 memset(pkt, 0, sizeof(AVPacket));
04394 av_init_packet(pkt);
04395 }
04396
04397 int retval = 0;
04398 if (!ic || ((retval = av_read_frame(ic, pkt)) < 0))
04399 {
04400 if (retval == -EAGAIN)
04401 continue;
04402
04403 SetEof(true);
04404 delete pkt;
04405 errno = -retval;
04406 LOG(VB_GENERAL, LOG_ERR, QString("decoding error") + ENO);
04407 return false;
04408 }
04409
04410 if (waitingForChange && pkt->pos >= readAdjust)
04411 FileChanged();
04412
04413 if (pkt->pos > readAdjust)
04414 pkt->pos -= readAdjust;
04415 }
04416
04417 if (!ic)
04418 {
04419 LOG(VB_GENERAL, LOG_ERR, LOC + "No context");
04420 av_free_packet(pkt);
04421 continue;
04422 }
04423
04424 if (pkt->stream_index >= (int)ic->nb_streams)
04425 {
04426 LOG(VB_GENERAL, LOG_ERR, LOC + "Bad stream");
04427 av_free_packet(pkt);
04428 continue;
04429 }
04430
04431 AVStream *curstream = ic->streams[pkt->stream_index];
04432
04433 if (!curstream)
04434 {
04435 LOG(VB_GENERAL, LOG_ERR, LOC + "Bad stream (NULL)");
04436 av_free_packet(pkt);
04437 continue;
04438 }
04439
04440 enum AVMediaType codec_type = curstream->codec->codec_type;
04441
04442 if (storevideoframes && codec_type == AVMEDIA_TYPE_VIDEO)
04443 {
04444 av_dup_packet(pkt);
04445 storedPackets.append(pkt);
04446 pkt = NULL;
04447 continue;
04448 }
04449
04450 if (codec_type == AVMEDIA_TYPE_VIDEO &&
04451 pkt->stream_index == selectedTrack[kTrackTypeVideo].av_stream_index)
04452 {
04453 if (!PreProcessVideoPacket(curstream, pkt))
04454 continue;
04455
04456
04457
04458 if (m_parent->IsErrored())
04459 {
04460 av_free_packet(pkt);
04461 delete pkt;
04462 return false;
04463 }
04464 }
04465
04466 if (codec_type == AVMEDIA_TYPE_SUBTITLE &&
04467 curstream->codec->codec_id == CODEC_ID_TEXT)
04468 {
04469 ProcessRawTextPacket(pkt);
04470 av_free_packet(pkt);
04471 continue;
04472 }
04473
04474 if (codec_type == AVMEDIA_TYPE_SUBTITLE &&
04475 curstream->codec->codec_id == CODEC_ID_DVB_TELETEXT)
04476 {
04477 ProcessDVBDataPacket(curstream, pkt);
04478 av_free_packet(pkt);
04479 continue;
04480 }
04481
04482 if (codec_type == AVMEDIA_TYPE_DATA)
04483 {
04484 ProcessDataPacket(curstream, pkt, decodetype);
04485 av_free_packet(pkt);
04486 continue;
04487 }
04488
04489 if (!curstream->codec->codec)
04490 {
04491 LOG(VB_PLAYBACK, LOG_ERR, LOC +
04492 QString("No codec for stream index %1, type(%2) id(%3:%4)")
04493 .arg(pkt->stream_index)
04494 .arg(ff_codec_type_string(codec_type))
04495 .arg(ff_codec_id_string(curstream->codec->codec_id))
04496 .arg(curstream->codec->codec_id));
04497 av_free_packet(pkt);
04498 continue;
04499 }
04500
04501 have_err = false;
04502
04503 switch (codec_type)
04504 {
04505 case AVMEDIA_TYPE_AUDIO:
04506 {
04507 if (!ProcessAudioPacket(curstream, pkt, decodetype))
04508 have_err = true;
04509 else
04510 GenerateDummyVideoFrames();
04511 break;
04512 }
04513
04514 case AVMEDIA_TYPE_VIDEO:
04515 {
04516 if (pkt->stream_index != selectedTrack[kTrackTypeVideo].av_stream_index)
04517 {
04518 break;
04519 }
04520
04521 if (pkt->pts != (int64_t) AV_NOPTS_VALUE)
04522 {
04523 lastccptsu = (long long)
04524 (av_q2d(curstream->time_base)*pkt->pts*1000000);
04525 }
04526
04527 if (!(decodetype & kDecodeVideo))
04528 {
04529 framesPlayed++;
04530 gotVideoFrame = 1;
04531 break;
04532 }
04533
04534 if (!ProcessVideoPacket(curstream, pkt))
04535 have_err = true;
04536 break;
04537 }
04538
04539 case AVMEDIA_TYPE_SUBTITLE:
04540 {
04541 if (!ProcessSubtitlePacket(curstream, pkt))
04542 have_err = true;
04543 break;
04544 }
04545
04546 default:
04547 {
04548 AVCodecContext *enc = curstream->codec;
04549 LOG(VB_GENERAL, LOG_ERR, LOC +
04550 QString("Decoding - id(%1) type(%2)")
04551 .arg(ff_codec_id_string(enc->codec_id))
04552 .arg(ff_codec_type_string(enc->codec_type)));
04553 have_err = true;
04554 break;
04555 }
04556 }
04557
04558 if (!have_err)
04559 frame_decoded = 1;
04560
04561 av_free_packet(pkt);
04562 }
04563
04564 if (pkt)
04565 delete pkt;
04566
04567 return true;
04568 }
04569
04570 bool AvFormatDecoder::HasVideo(const AVFormatContext *ic)
04571 {
04572 if (ic && ic->cur_pmt_sect)
04573 {
04574 const PESPacket pes = PESPacket::ViewData(ic->cur_pmt_sect);
04575 const PSIPTable psip(pes);
04576 const ProgramMapTable pmt(psip);
04577
04578 for (uint i = 0; i < pmt.StreamCount(); i++)
04579 {
04580
04581
04582
04583 if (pmt.IsVideo(i, "dvb"))
04584 return true;
04585
04586
04587 if ((i == (uint)selectedTrack[kTrackTypeVideo].av_stream_index) &&
04588 (pmt.StreamType(i) == StreamID::PrivData))
04589 {
04590 return true;
04591 }
04592 }
04593 }
04594
04595 return GetTrackCount(kTrackTypeVideo);
04596 }
04597
04598 bool AvFormatDecoder::GenerateDummyVideoFrames(void)
04599 {
04600 while (needDummyVideoFrames && m_parent &&
04601 m_parent->GetFreeVideoFrames())
04602 {
04603 VideoFrame *frame = m_parent->GetNextVideoFrame();
04604 if (!frame)
04605 return false;
04606
04607 m_parent->ClearDummyVideoFrame(frame);
04608 m_parent->ReleaseNextVideoFrame(frame, lastvpts);
04609 m_parent->DeLimboFrame(frame);
04610
04611 frame->interlaced_frame = 0;
04612 frame->top_field_first = 1;
04613 frame->repeat_pict = 0;
04614 frame->frameNumber = framesPlayed;
04615 frame->dummy = 1;
04616
04617 decoded_video_frame = frame;
04618 framesPlayed++;
04619 gotVideoFrame = true;
04620 }
04621 return true;
04622 }
04623
04624 QString AvFormatDecoder::GetCodecDecoderName(void) const
04625 {
04626 if (private_dec)
04627 return private_dec->GetName();
04628 return get_decoder_name(video_codec_id);
04629 }
04630
04631 QString AvFormatDecoder::GetRawEncodingType(void)
04632 {
04633 int stream = selectedTrack[kTrackTypeVideo].av_stream_index;
04634 if (stream < 0 || !ic)
04635 return QString();
04636 return ff_codec_id_string(ic->streams[stream]->codec->codec_id);
04637 }
04638
04639 void *AvFormatDecoder::GetVideoCodecPrivate(void)
04640 {
04641 return NULL;
04642 }
04643
04644 void AvFormatDecoder::SetDisablePassThrough(bool disable)
04645 {
04646
04647
04648 if (disable_passthru)
04649 return;
04650
04651 if (selectedTrack[kTrackTypeAudio].av_stream_index < 0)
04652 {
04653 disable_passthru = disable;
04654 return;
04655 }
04656
04657 if (disable != disable_passthru)
04658 {
04659 disable_passthru = disable;
04660 QString msg = (disable) ? "Disabling" : "Allowing";
04661 LOG(VB_AUDIO, LOG_INFO, LOC + msg + " pass through");
04662
04663
04664 QMutexLocker locker(avcodeclock);
04665 SetupAudioStream();
04666 }
04667 }
04668
04669 inline bool AvFormatDecoder::DecoderWillDownmix(const AVCodecContext *ctx)
04670 {
04671
04672
04673 if (m_audio->CanDownmix() && AudioOutputUtil::has_hardware_fpu())
04674 return false;
04675 if (!m_audio->CanDownmix())
04676 return true;
04677
04678 switch (ctx->codec_id)
04679 {
04680 case CODEC_ID_AC3:
04681 case CODEC_ID_TRUEHD:
04682 case CODEC_ID_EAC3:
04683 return true;
04684 default:
04685 return false;
04686 }
04687 }
04688
04689 bool AvFormatDecoder::DoPassThrough(const AVCodecContext *ctx, bool withProfile)
04690 {
04691 bool passthru;
04692
04693
04694
04695 if (!withProfile && ctx->codec_id == CODEC_ID_DTS && !m_audio->CanDTSHD())
04696 passthru = m_audio->CanPassthrough(ctx->sample_rate, ctx->channels,
04697 ctx->codec_id, FF_PROFILE_DTS);
04698 else
04699 passthru = m_audio->CanPassthrough(ctx->sample_rate, ctx->channels,
04700 ctx->codec_id, ctx->profile);
04701
04702 passthru &= !disable_passthru;
04703
04704 return passthru;
04705 }
04706
04714 bool AvFormatDecoder::SetupAudioStream(void)
04715 {
04716 AudioInfo info;
04717 AVStream *curstream = NULL;
04718 AVCodecContext *ctx = NULL;
04719 AudioInfo old_in = audioIn;
04720 bool using_passthru = false;
04721 int orig_channels = 2;
04722
04723 if ((currentTrack[kTrackTypeAudio] >= 0) && ic &&
04724 (selectedTrack[kTrackTypeAudio].av_stream_index <=
04725 (int) ic->nb_streams) &&
04726 (curstream = ic->streams[selectedTrack[kTrackTypeAudio]
04727 .av_stream_index]))
04728 {
04729 assert(curstream);
04730 assert(curstream->codec);
04731 ctx = curstream->codec;
04732 orig_channels = selectedTrack[kTrackTypeAudio].orig_num_channels;
04733 AudioFormat fmt;
04734
04735 switch (ctx->sample_fmt)
04736 {
04737 case AV_SAMPLE_FMT_U8: fmt = FORMAT_U8; break;
04738 case AV_SAMPLE_FMT_S16: fmt = FORMAT_S16; break;
04739 case AV_SAMPLE_FMT_FLT: fmt = FORMAT_FLT; break;
04740 case AV_SAMPLE_FMT_DBL: fmt = FORMAT_NONE; break;
04741 case AV_SAMPLE_FMT_S32:
04742 switch (ctx->bits_per_raw_sample)
04743 {
04744 case 0: fmt = FORMAT_S32; break;
04745 case 24: fmt = FORMAT_S24; break;
04746 case 32: fmt = FORMAT_S32; break;
04747 default: fmt = FORMAT_NONE;
04748 }
04749 break;
04750 default: fmt = FORMAT_NONE;
04751 }
04752
04753 if (fmt == FORMAT_NONE)
04754 {
04755 int bps = av_get_bytes_per_sample(ctx->sample_fmt) << 3;
04756 if (ctx->sample_fmt == AV_SAMPLE_FMT_S32 &&
04757 ctx->bits_per_raw_sample)
04758 bps = ctx->bits_per_raw_sample;
04759 LOG(VB_GENERAL, LOG_ERR, LOC +
04760 QString("Unsupported sample format with %1 bits").arg(bps));
04761 return false;
04762 }
04763
04764 using_passthru = DoPassThrough(ctx, false);
04765
04766 ctx->request_channels = ctx->channels;
04767
04768 if (!using_passthru &&
04769 ctx->channels > (int)m_audio->GetMaxChannels() &&
04770 DecoderWillDownmix(ctx))
04771 {
04772 ctx->request_channels = m_audio->GetMaxChannels();
04773 }
04774
04775 info = AudioInfo(ctx->codec_id, fmt, ctx->sample_rate,
04776 ctx->channels, using_passthru, orig_channels,
04777 ctx->codec_id == CODEC_ID_DTS ? ctx->profile : 0);
04778 }
04779
04780 if (!ctx)
04781 {
04782 if (GetTrackCount(kTrackTypeAudio))
04783 LOG(VB_PLAYBACK, LOG_INFO, LOC +
04784 "No codec context. Returning false");
04785 return false;
04786 }
04787
04788 if (info == audioIn)
04789 return false;
04790
04791 LOG(VB_AUDIO, LOG_INFO, LOC + "Initializing audio parms from " +
04792 QString("audio track #%1").arg(currentTrack[kTrackTypeAudio]+1));
04793
04794 audioOut = audioIn = info;
04795
04796 LOG(VB_AUDIO, LOG_INFO, LOC + "Audio format changed " +
04797 QString("\n\t\t\tfrom %1 to %2")
04798 .arg(old_in.toString()).arg(audioOut.toString()));
04799
04800 m_audio->SetAudioParams(audioOut.format, orig_channels,
04801 ctx->request_channels,
04802 audioOut.codec_id, audioOut.sample_rate,
04803 audioOut.do_passthru, audioOut.codec_profile);
04804 m_audio->ReinitAudio();
04805
04806 if (LCD *lcd = LCD::Get())
04807 {
04808 LCDAudioFormatSet audio_format;
04809
04810 switch (ctx->codec_id)
04811 {
04812 case CODEC_ID_MP2:
04813 audio_format = AUDIO_MPEG2;
04814 break;
04815 case CODEC_ID_MP3:
04816 audio_format = AUDIO_MP3;
04817 break;
04818 case CODEC_ID_AC3:
04819 audio_format = AUDIO_AC3;
04820 break;
04821 case CODEC_ID_DTS:
04822 audio_format = AUDIO_DTS;
04823 break;
04824 case CODEC_ID_VORBIS:
04825 audio_format = AUDIO_OGG;
04826 break;
04827 case CODEC_ID_WMAV1:
04828 audio_format = AUDIO_WMA;
04829 break;
04830 case CODEC_ID_WMAV2:
04831 audio_format = AUDIO_WMA2;
04832 break;
04833 default:
04834 audio_format = AUDIO_WAV;
04835 break;
04836 }
04837
04838 lcd->setAudioFormatLEDs(audio_format, true);
04839
04840 if (audioOut.do_passthru)
04841 lcd->setVariousLEDs(VARIOUS_SPDIF, true);
04842 else
04843 lcd->setVariousLEDs(VARIOUS_SPDIF, false);
04844
04845 switch (audioIn.channels)
04846 {
04847 case 0:
04848
04849
04850 case 1:
04851 case 2:
04852
04853
04854 lcd->setSpeakerLEDs(SPEAKER_LR, true);
04855 break;
04856 case 3:
04857 case 4:
04858 case 5:
04859 case 6:
04860 lcd->setSpeakerLEDs(SPEAKER_51, true);
04861 break;
04862 default:
04863 lcd->setSpeakerLEDs(SPEAKER_71, true);
04864 break;
04865 }
04866
04867 }
04868 return true;
04869 }
04870
04871 void AvFormatDecoder::av_update_stream_timings_video(AVFormatContext *ic)
04872 {
04873 int64_t start_time, start_time1, end_time, end_time1;
04874 int64_t duration, duration1, filesize;
04875 AVStream *st = NULL;
04876
04877 start_time = INT64_MAX;
04878 end_time = INT64_MIN;
04879
04880 for (uint i = 0; i < ic->nb_streams; i++)
04881 {
04882 AVStream *st1 = ic->streams[i];
04883 if (st1 && st1->codec->codec_type == AVMEDIA_TYPE_VIDEO)
04884 {
04885 st = st1;
04886 break;
04887 }
04888 }
04889 if (!st)
04890 return;
04891
04892 duration = INT64_MIN;
04893 if (st->start_time != (int64_t)AV_NOPTS_VALUE && st->time_base.den) {
04894 start_time1= av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q);
04895 if (start_time1 < start_time)
04896 start_time = start_time1;
04897 if (st->duration != (int64_t)AV_NOPTS_VALUE) {
04898 end_time1 = start_time1 +
04899 av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
04900 if (end_time1 > end_time)
04901 end_time = end_time1;
04902 }
04903 }
04904 if (st->duration != (int64_t)AV_NOPTS_VALUE) {
04905 duration1 = av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
04906 if (duration1 > duration)
04907 duration = duration1;
04908 }
04909 if (start_time != INT64_MAX) {
04910 ic->start_time = start_time;
04911 if (end_time != INT64_MIN) {
04912 if (end_time - start_time > duration)
04913 duration = end_time - start_time;
04914 }
04915 }
04916 if (duration != INT64_MIN) {
04917 ic->duration = duration;
04918 if (ic->pb && (filesize = avio_size(ic->pb)) > 0) {
04919
04920 ic->bit_rate = (double)filesize * 8.0 * AV_TIME_BASE /
04921 (double)ic->duration;
04922 }
04923 }
04924 }
04925
04926