FIX: [droid] set "remote as keyboard" default to true
[vuplus_xbmc] / xbmc / cores / dvdplayer / DVDFileInfo.cpp
1 /*
2  *      Copyright (C) 2005-2013 Team XBMC
3  *      http://xbmc.org
4  *
5  *  This Program is free software; you can redistribute it and/or modify
6  *  it under the terms of the GNU General Public License as published by
7  *  the Free Software Foundation; either version 2, or (at your option)
8  *  any later version.
9  *
10  *  This Program is distributed in the hope that it will be useful,
11  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  *  GNU General Public License for more details.
14  *
15  *  You should have received a copy of the GNU General Public License
16  *  along with XBMC; see the file COPYING.  If not, see
17  *  <http://www.gnu.org/licenses/>.
18  *
19  */
20
21 #include "threads/SystemClock.h"
22 #include "DVDFileInfo.h"
23 #include "FileItem.h"
24 #include "settings/AdvancedSettings.h"
25 #include "pictures/Picture.h"
26 #include "video/VideoInfoTag.h"
27 #include "filesystem/StackDirectory.h"
28 #include "utils/log.h"
29 #include "utils/TimeUtils.h"
30 #include "utils/URIUtils.h"
31
32 #include "DVDClock.h"
33 #include "DVDStreamInfo.h"
34 #include "DVDInputStreams/DVDInputStream.h"
35 #ifdef HAVE_LIBBLURAY
36 #include "DVDInputStreams/DVDInputStreamBluray.h"
37 #endif
38 #include "DVDInputStreams/DVDFactoryInputStream.h"
39 #include "DVDDemuxers/DVDDemux.h"
40 #include "DVDDemuxers/DVDDemuxUtils.h"
41 #include "DVDDemuxers/DVDFactoryDemuxer.h"
42 #include "DVDDemuxers/DVDDemuxFFmpeg.h"
43 #include "DVDCodecs/DVDCodecs.h"
44 #include "DVDCodecs/DVDFactoryCodec.h"
45 #include "DVDCodecs/Video/DVDVideoCodec.h"
46 #include "DVDCodecs/Video/DVDVideoCodecFFmpeg.h"
47 #include "DVDDemuxers/DVDDemuxVobsub.h"
48
49 #include "DllAvCodec.h"
50 #include "DllSwScale.h"
51 #include "filesystem/File.h"
52 #include "TextureCache.h"
53 #include "Util.h"
54 #include "utils/LangCodeExpander.h"
55
56
57 bool CDVDFileInfo::GetFileDuration(const CStdString &path, int& duration)
58 {
59   std::auto_ptr<CDVDInputStream> input;
60   std::auto_ptr<CDVDDemux> demux;
61
62   input.reset(CDVDFactoryInputStream::CreateInputStream(NULL, path, ""));
63   if (!input.get())
64     return false;
65
66   if (!input->Open(path, ""))
67     return false;
68
69   demux.reset(CDVDFactoryDemuxer::CreateDemuxer(input.get()));
70   if (!demux.get())
71     return false;
72
73   duration = demux->GetStreamLength();
74   if (duration > 0)
75     return true;
76   else
77     return false;
78 }
79
80 int DegreeToOrientation(int degrees)
81 {
82   switch(degrees)
83   {
84     case 90:
85       return 5;
86     case 180:
87       return 2;
88     case 270:
89       return 7;
90     default:
91       return 0;
92   }
93 }
94
95 bool CDVDFileInfo::ExtractThumb(const CStdString &strPath, CTextureDetails &details, CStreamDetails *pStreamDetails)
96 {
97   std::string redactPath = CURL::GetRedacted(strPath);
98   unsigned int nTime = XbmcThreads::SystemClockMillis();
99   CDVDInputStream *pInputStream = CDVDFactoryInputStream::CreateInputStream(NULL, strPath, "");
100   if (!pInputStream)
101   {
102     CLog::Log(LOGERROR, "InputStream: Error creating stream for %s", redactPath.c_str());
103     return false;
104   }
105
106   if (pInputStream->IsStreamType(DVDSTREAM_TYPE_DVD))
107   {
108     CLog::Log(LOGERROR, "InputStream: dvd streams not supported for thumb extraction, file: %s", redactPath.c_str());
109     delete pInputStream;
110     return false;
111   }
112
113   if (!pInputStream->Open(strPath.c_str(), ""))
114   {
115     CLog::Log(LOGERROR, "InputStream: Error opening, %s", redactPath.c_str());
116     if (pInputStream)
117       delete pInputStream;
118     return false;
119   }
120
121   CDVDDemux *pDemuxer = NULL;
122
123   try
124   {
125     pDemuxer = CDVDFactoryDemuxer::CreateDemuxer(pInputStream);
126     if(!pDemuxer)
127     {
128       delete pInputStream;
129       CLog::Log(LOGERROR, "%s - Error creating demuxer", __FUNCTION__);
130       return false;
131     }
132   }
133   catch(...)
134   {
135     CLog::Log(LOGERROR, "%s - Exception thrown when opening demuxer", __FUNCTION__);
136     if (pDemuxer)
137       delete pDemuxer;
138     delete pInputStream;
139     return false;
140   }
141
142   if (pStreamDetails)
143   {
144     DemuxerToStreamDetails(pInputStream, pDemuxer, *pStreamDetails, strPath);
145
146     //extern subtitles
147     std::vector<CStdString> filenames;
148     CStdString video_path;
149     if (strPath.empty())
150       video_path = pInputStream->GetFileName();
151     else
152       video_path = strPath;
153
154     CUtil::ScanForExternalSubtitles(video_path, filenames);
155
156     for(unsigned int i=0;i<filenames.size();i++)
157     {
158       // if vobsub subtitle:
159       if (URIUtils::GetExtension(filenames[i]) == ".idx")
160       {
161         CStdString strSubFile;
162         if ( CUtil::FindVobSubPair(filenames, filenames[i], strSubFile) )
163           AddExternalSubtitleToDetails(video_path, *pStreamDetails, filenames[i], strSubFile);
164       }
165       else
166       {
167         if ( !CUtil::IsVobSub(filenames, filenames[i]) )
168         {
169           AddExternalSubtitleToDetails(video_path, *pStreamDetails, filenames[i]);
170         }
171       }
172     }
173   }
174
175   int nVideoStream = -1;
176   for (int i = 0; i < pDemuxer->GetNrOfStreams(); i++)
177   {
178     CDemuxStream* pStream = pDemuxer->GetStream(i);
179     if (pStream)
180     {
181       if(pStream->type == STREAM_VIDEO)
182         nVideoStream = i;
183       else
184         pStream->SetDiscard(AVDISCARD_ALL);
185     }
186   }
187
188   bool bOk = false;
189   int packetsTried = 0;
190
191   if (nVideoStream != -1)
192   {
193     CDVDVideoCodec *pVideoCodec;
194
195     CDVDStreamInfo hint(*pDemuxer->GetStream(nVideoStream), true);
196     hint.software = true;
197
198     if (hint.codec == AV_CODEC_ID_MPEG2VIDEO || hint.codec == AV_CODEC_ID_MPEG1VIDEO)
199     {
200       // libmpeg2 is not thread safe so use ffmepg for mpeg2/mpeg1 thumb extraction
201       CDVDCodecOptions dvdOptions;
202       pVideoCodec = CDVDFactoryCodec::OpenCodec(new CDVDVideoCodecFFmpeg(), hint, dvdOptions);
203     }
204     else
205     {
206       pVideoCodec = CDVDFactoryCodec::CreateVideoCodec( hint );
207     }
208
209     if (pVideoCodec)
210     {
211       int nTotalLen = pDemuxer->GetStreamLength();
212       int nSeekTo = nTotalLen / 3;
213
214       CLog::Log(LOGDEBUG,"%s - seeking to pos %dms (total: %dms) in %s", __FUNCTION__, nSeekTo, nTotalLen, redactPath.c_str());
215       if (pDemuxer->SeekTime(nSeekTo, true))
216       {
217         int iDecoderState = VC_ERROR;
218         DVDVideoPicture picture;
219
220         memset(&picture, 0, sizeof(picture));
221
222         // num streams * 80 frames, should get a valid frame, if not abort.
223         int abort_index = pDemuxer->GetNrOfStreams() * 80;
224         do
225         {
226           DemuxPacket* pPacket = pDemuxer->Read();
227           packetsTried++;
228
229           if (!pPacket)
230             break;
231
232           if (pPacket->iStreamId != nVideoStream)
233           {
234             CDVDDemuxUtils::FreeDemuxPacket(pPacket);
235             continue;
236           }
237
238           iDecoderState = pVideoCodec->Decode(pPacket->pData, pPacket->iSize, pPacket->dts, pPacket->pts);
239           CDVDDemuxUtils::FreeDemuxPacket(pPacket);
240
241           if (iDecoderState & VC_ERROR)
242             break;
243
244           if (iDecoderState & VC_PICTURE)
245           {
246             memset(&picture, 0, sizeof(DVDVideoPicture));
247             if (pVideoCodec->GetPicture(&picture))
248             {
249               if(!(picture.iFlags & DVP_FLAG_DROPPED))
250                 break;
251             }
252           }
253
254         } while (abort_index--);
255
256         if (iDecoderState & VC_PICTURE && !(picture.iFlags & DVP_FLAG_DROPPED))
257         {
258           {
259             unsigned int nWidth = g_advancedSettings.GetThumbSize();
260             double aspect = (double)picture.iDisplayWidth / (double)picture.iDisplayHeight;
261             if(hint.forced_aspect && hint.aspect != 0)
262               aspect = hint.aspect;
263             unsigned int nHeight = (unsigned int)((double)g_advancedSettings.GetThumbSize() / aspect);
264
265             DllSwScale dllSwScale;
266             dllSwScale.Load();
267
268             uint8_t *pOutBuf = new uint8_t[nWidth * nHeight * 4];
269             struct SwsContext *context = dllSwScale.sws_getContext(picture.iWidth, picture.iHeight,
270                   PIX_FMT_YUV420P, nWidth, nHeight, PIX_FMT_BGRA, SWS_FAST_BILINEAR | SwScaleCPUFlags(), NULL, NULL, NULL);
271
272             if (context)
273             {
274               uint8_t *src[] = { picture.data[0], picture.data[1], picture.data[2], 0 };
275               int     srcStride[] = { picture.iLineSize[0], picture.iLineSize[1], picture.iLineSize[2], 0 };
276               uint8_t *dst[] = { pOutBuf, 0, 0, 0 };
277               int     dstStride[] = { (int)nWidth*4, 0, 0, 0 };
278               int orientation = DegreeToOrientation(hint.orientation);
279               dllSwScale.sws_scale(context, src, srcStride, 0, picture.iHeight, dst, dstStride);
280               dllSwScale.sws_freeContext(context);
281
282               details.width = nWidth;
283               details.height = nHeight;
284               CPicture::CacheTexture(pOutBuf, nWidth, nHeight, nWidth * 4, orientation, nWidth, nHeight, CTextureCache::GetCachedPath(details.file));
285               bOk = true;
286             }
287
288             dllSwScale.Unload();
289             delete [] pOutBuf;
290           }
291         }
292         else
293         {
294           CLog::Log(LOGDEBUG,"%s - decode failed in %s after %d packets.", __FUNCTION__, redactPath.c_str(), packetsTried);
295         }
296       }
297       delete pVideoCodec;
298     }
299   }
300
301   if (pDemuxer)
302     delete pDemuxer;
303
304   delete pInputStream;
305
306   if(!bOk)
307   {
308     XFILE::CFile file;
309     if(file.OpenForWrite(CTextureCache::GetCachedPath(details.file)))
310       file.Close();
311   }
312
313   unsigned int nTotalTime = XbmcThreads::SystemClockMillis() - nTime;
314   CLog::Log(LOGDEBUG,"%s - measured %u ms to extract thumb from file <%s> in %d packets. ", __FUNCTION__, nTotalTime, redactPath.c_str(), packetsTried);
315   return bOk;
316 }
317
318 /**
319  * \brief Open the item pointed to by pItem and extact streamdetails
320  * \return true if the stream details have changed
321  */
322 bool CDVDFileInfo::GetFileStreamDetails(CFileItem *pItem)
323 {
324   if (!pItem)
325     return false;
326
327   CStdString strFileNameAndPath;
328   if (pItem->HasVideoInfoTag())
329     strFileNameAndPath = pItem->GetVideoInfoTag()->m_strFileNameAndPath;
330
331   if (strFileNameAndPath.empty())
332     strFileNameAndPath = pItem->GetPath();
333
334   CStdString playablePath = strFileNameAndPath;
335   if (URIUtils::IsStack(playablePath))
336     playablePath = XFILE::CStackDirectory::GetFirstStackedFile(playablePath);
337
338   CDVDInputStream *pInputStream = CDVDFactoryInputStream::CreateInputStream(NULL, playablePath, "");
339   if (!pInputStream)
340     return false;
341
342   if (pInputStream->IsStreamType(DVDSTREAM_TYPE_DVD) || !pInputStream->Open(playablePath.c_str(), ""))
343   {
344     delete pInputStream;
345     return false;
346   }
347
348   CDVDDemux *pDemuxer = CDVDFactoryDemuxer::CreateDemuxer(pInputStream);
349   if (pDemuxer)
350   {
351     bool retVal = DemuxerToStreamDetails(pInputStream, pDemuxer, pItem->GetVideoInfoTag()->m_streamDetails, strFileNameAndPath);
352     delete pDemuxer;
353     delete pInputStream;
354     return retVal;
355   }
356   else
357   {
358     delete pInputStream;
359     return false;
360   }
361 }
362
363 bool CDVDFileInfo::DemuxerToStreamDetails(CDVDInputStream *pInputStream, CDVDDemux *pDemuxer, const std::vector<CStreamDetailSubtitle> &subs, CStreamDetails &details)
364 {
365   bool result = DemuxerToStreamDetails(pInputStream, pDemuxer, details);
366   for (unsigned int i = 0; i < subs.size(); i++)
367   {
368     CStreamDetailSubtitle* sub = new CStreamDetailSubtitle();
369     sub->m_strLanguage = subs[i].m_strLanguage;
370     details.AddStream(sub);
371     result = true;
372   }
373   return result;
374 }
375
376 /* returns true if details have been added */
377 bool CDVDFileInfo::DemuxerToStreamDetails(CDVDInputStream *pInputStream, CDVDDemux *pDemux, CStreamDetails &details, const CStdString &path)
378 {
379   bool retVal = false;
380   details.Reset();
381
382   for (int iStream=0; iStream<pDemux->GetNrOfStreams(); iStream++)
383   {
384     CDemuxStream *stream = pDemux->GetStream(iStream);
385     if (stream->type == STREAM_VIDEO)
386     {
387       CStreamDetailVideo *p = new CStreamDetailVideo();
388       p->m_iWidth = ((CDemuxStreamVideo *)stream)->iWidth;
389       p->m_iHeight = ((CDemuxStreamVideo *)stream)->iHeight;
390       p->m_fAspect = ((CDemuxStreamVideo *)stream)->fAspect;
391       if (p->m_fAspect == 0.0f)
392         p->m_fAspect = (float)p->m_iWidth / p->m_iHeight;
393       pDemux->GetStreamCodecName(iStream, p->m_strCodec);
394       p->m_iDuration = pDemux->GetStreamLength();
395       p->m_strStereoMode = ((CDemuxStreamVideo *)stream)->stereo_mode;
396
397       // stack handling
398       if (URIUtils::IsStack(path))
399       {
400         CFileItemList files;
401         XFILE::CStackDirectory stack;
402         stack.GetDirectory(path, files);
403
404         // skip first path as we already know the duration
405         for (int i = 1; i < files.Size(); i++)
406         {
407            int duration = 0;
408            if (CDVDFileInfo::GetFileDuration(files[i]->GetPath(), duration))
409              p->m_iDuration = p->m_iDuration + duration;
410         }
411       }
412
413       // finally, calculate seconds
414       if (p->m_iDuration > 0)
415         p->m_iDuration = p->m_iDuration / 1000;
416
417       details.AddStream(p);
418       retVal = true;
419     }
420
421     else if (stream->type == STREAM_AUDIO)
422     {
423       CStreamDetailAudio *p = new CStreamDetailAudio();
424       p->m_iChannels = ((CDemuxStreamAudio *)stream)->iChannels;
425       p->m_strLanguage = stream->language;
426       pDemux->GetStreamCodecName(iStream, p->m_strCodec);
427       details.AddStream(p);
428       retVal = true;
429     }
430
431     else if (stream->type == STREAM_SUBTITLE)
432     {
433       CStreamDetailSubtitle *p = new CStreamDetailSubtitle();
434       p->m_strLanguage = stream->language;
435       details.AddStream(p);
436       retVal = true;
437     }
438   }  /* for iStream */
439
440   details.DetermineBestStreams();
441 #ifdef HAVE_LIBBLURAY
442   // correct bluray runtime. we need the duration from the input stream, not the demuxer.
443   if (pInputStream->IsStreamType(DVDSTREAM_TYPE_BLURAY))
444   {
445     if(((CDVDInputStreamBluray*)pInputStream)->GetTotalTime() > 0)
446     {
447       ((CStreamDetailVideo*)details.GetNthStream(CStreamDetail::VIDEO,0))->m_iDuration = ((CDVDInputStreamBluray*)pInputStream)->GetTotalTime() / 1000;
448     }
449   }
450 #endif
451   return retVal;
452 }
453
454 bool CDVDFileInfo::AddExternalSubtitleToDetails(const CStdString &path, CStreamDetails &details, const std::string& filename, const std::string& subfilename)
455 {
456   std::string ext = URIUtils::GetExtension(filename);
457   std::string vobsubfile = subfilename;
458   if(ext == ".idx")
459   {
460     if (vobsubfile.empty())
461       vobsubfile = URIUtils::ReplaceExtension(filename, ".sub");
462
463     CDVDDemuxVobsub v;
464     if(!v.Open(filename, vobsubfile))
465       return false;
466
467     int count = v.GetNrOfStreams();
468
469     for(int i = 0; i < count; i++)
470     {
471       CStreamDetailSubtitle *dsub = new CStreamDetailSubtitle();
472       CDemuxStream* stream = v.GetStream(i);
473       std::string lang = stream->language;
474       dsub->m_strLanguage = g_LangCodeExpander.ConvertToISO6392T(lang);
475       details.AddStream(dsub);
476     }
477     return true;
478   }
479   if(ext == ".sub")
480   {
481     CStdString strReplace(URIUtils::ReplaceExtension(filename,".idx"));
482     if (XFILE::CFile::Exists(strReplace))
483       return false;
484   }
485
486   CStreamDetailSubtitle *dsub = new CStreamDetailSubtitle();
487   ExternalStreamInfo info;
488   CUtil::GetExternalStreamDetailsFromFilename(path, filename, info);
489   dsub->m_strLanguage = g_LangCodeExpander.ConvertToISO6392T(info.language);
490   details.AddStream(dsub);
491
492   return true;
493 }
494