Merge pull request #3034 from jhsrennie/win_paste
[vuplus_xbmc] / xbmc / Autorun.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 "system.h"
22
23 #ifdef HAS_DVD_DRIVE
24
25 #include "Autorun.h"
26 #include "Application.h"
27 #include "GUIPassword.h"
28 #include "GUIUserMessages.h"
29 #include "PlayListPlayer.h"
30 #include "filesystem/StackDirectory.h"
31 #include "filesystem/Directory.h"
32 #include "filesystem/DirectoryFactory.h"
33 #include "filesystem/File.h"
34 #include "profiles/ProfilesManager.h"
35 #include "settings/Settings.h"
36 #include "playlists/PlayList.h"
37 #include "guilib/GUIWindowManager.h"
38 #include "guilib/LocalizeStrings.h"
39 #include "storage/MediaManager.h"
40 #include "video/VideoDatabase.h"
41 #include "dialogs/GUIDialogYesNo.h"
42 #include "utils/URIUtils.h"
43 #include "utils/log.h"
44 #ifdef HAS_CDDA_RIPPER
45 #include "cdrip/CDDARipper.h"
46 #endif
47
48 using namespace std;
49 using namespace XFILE;
50 using namespace PLAYLIST;
51 using namespace MEDIA_DETECT;
52
53 CAutorun::CAutorun()
54 {
55   m_bEnable = true;
56 }
57
58 CAutorun::~CAutorun()
59 {}
60
61 void CAutorun::ExecuteAutorun(const CStdString& path, bool bypassSettings, bool ignoreplaying, bool startFromBeginning )
62 {
63   if ((!ignoreplaying && (g_application.IsPlayingAudio() || g_application.IsPlayingVideo() || g_windowManager.HasModalDialog())) || g_windowManager.GetActiveWindow() == WINDOW_LOGIN_SCREEN)
64     return ;
65
66   CCdInfo* pInfo = g_mediaManager.GetCdInfo(path);
67
68   if ( pInfo == NULL )
69     return ;
70
71   g_application.ResetScreenSaver();
72   g_application.WakeUpScreenSaverAndDPMS();  // turn off the screensaver if it's active
73 #ifdef HAS_CDDA_RIPPER
74   if (CSettings::Get().GetInt("audiocds.autoaction") == AUTOCD_RIP && 
75       pInfo->IsAudio(1) && !CProfilesManager::Get().GetCurrentProfile().musicLocked())
76   {
77     CCDDARipper::GetInstance().RipCD();
78   }
79   else
80 #endif
81   PlayDisc(path, bypassSettings, startFromBeginning);
82 }
83
84 bool CAutorun::PlayDisc(const CStdString& path, bool bypassSettings, bool startFromBeginning)
85 {
86   if ( !bypassSettings && !CSettings::Get().GetInt("audiocds.autoaction") == AUTOCD_PLAY && !CSettings::Get().GetBool("dvds.autorun"))
87     return false;
88
89   int nSize = g_playlistPlayer.GetPlaylist( PLAYLIST_MUSIC ).size();
90   int nAddedToPlaylist = 0;
91
92   CStdString mediaPath;
93
94   CCdInfo* pInfo = g_mediaManager.GetCdInfo(path);
95   if (pInfo == NULL)
96     return false;
97
98   if (mediaPath.IsEmpty() && pInfo->IsAudio(1))
99     mediaPath = "cdda://local/";
100
101   if (mediaPath.IsEmpty() && (pInfo->IsISOUDF(1) || pInfo->IsISOHFS(1) || pInfo->IsIso9660(1) || pInfo->IsIso9660Interactive(1)))
102     mediaPath = "iso9660://";
103
104   if (mediaPath.IsEmpty())
105     mediaPath = path;
106
107 #ifdef TARGET_WINDOWS
108   if (mediaPath.IsEmpty() || mediaPath.CompareNoCase("iso9660://") == 0)
109     mediaPath = g_mediaManager.TranslateDevicePath("");
110 #endif
111
112   auto_ptr<IDirectory> pDir ( CDirectoryFactory::Create( mediaPath ));
113   bool bPlaying = RunDisc(pDir.get(), mediaPath, nAddedToPlaylist, true, bypassSettings, startFromBeginning);
114
115   if ( !bPlaying && nAddedToPlaylist > 0 )
116   {
117     CGUIMessage msg( GUI_MSG_PLAYLIST_CHANGED, 0, 0 );
118     g_windowManager.SendMessage( msg );
119     g_playlistPlayer.SetCurrentPlaylist(PLAYLIST_MUSIC);
120     // Start playing the items we inserted
121     return g_playlistPlayer.Play(nSize);
122   }
123
124   return bPlaying;
125 }
126
127 /**
128  * This method tries to determine what type of disc is located in the given drive and starts to play the content appropriately.
129  */
130 bool CAutorun::RunDisc(IDirectory* pDir, const CStdString& strDrive, int& nAddedToPlaylist, bool bRoot, bool bypassSettings /* = false */, bool startFromBeginning /* = false */)
131 {
132   bool bPlaying(false);
133   CFileItemList vecItems;
134
135   if ( !pDir->GetDirectory( strDrive, vecItems ) )
136   {
137     return false;
138   }
139
140   // Sorting necessary for easier HDDVD handling
141   vecItems.Sort(SortByLabel, SortOrderAscending);
142
143   bool bAllowVideo = true;
144 //  bool bAllowPictures = true;
145   bool bAllowMusic = true;
146   if (!g_passwordManager.IsMasterLockUnlocked(false))
147   {
148     bAllowVideo = !CProfilesManager::Get().GetCurrentProfile().videoLocked();
149 //    bAllowPictures = !CProfilesManager::Get().GetCurrentProfile().picturesLocked();
150     bAllowMusic = !CProfilesManager::Get().GetCurrentProfile().musicLocked();
151   }
152
153   // is this a root folder we have to check the content to determine a disc type
154   if( bRoot )
155   {
156     CStdString hddvdname = "";
157     CFileItemPtr phddvdItem;
158
159     // check root folders next, for normal structured dvd's
160     for (int i = 0; i < vecItems.Size(); i++)
161     {
162       CFileItemPtr pItem = vecItems[i];
163
164       // is the current item a (non system) folder?
165       if (pItem->m_bIsFolder && pItem->GetPath() != "." && pItem->GetPath() != "..")
166       {
167         CStdString name = pItem->GetPath();
168         URIUtils::RemoveSlashAtEnd(name);
169         name = URIUtils::GetFileName(name);
170
171         // Check if the current foldername indicates a DVD structure (name is "VIDEO_TS")
172         if (name.Equals("VIDEO_TS") && bAllowVideo
173         && (bypassSettings || CSettings::Get().GetBool("dvds.autorun")))
174         {
175           CStdString path = URIUtils::AddFileToFolder(pItem->GetPath(), "VIDEO_TS.IFO");
176           if(!CFile::Exists(path))
177             path = URIUtils::AddFileToFolder(pItem->GetPath(), "video_ts.ifo");
178           CFileItem item(path, false);
179           item.SetLabel(g_mediaManager.GetDiskLabel(strDrive));
180           item.GetVideoInfoTag()->m_strFileNameAndPath = g_mediaManager.GetDiskUniqueId(strDrive);
181
182           if (!startFromBeginning && !item.GetVideoInfoTag()->m_strFileNameAndPath.IsEmpty())
183             item.m_lStartOffset = STARTOFFSET_RESUME;
184
185           g_application.PlayFile(item, false);
186           bPlaying = true;
187           return true;
188         }
189
190         // Check if the current foldername indicates a Blu-Ray structure (default is "BDMV").
191         // A BR should also include an "AACS" folder for encryption, Sony-BRs can also include update folders for PS3 (PS3_UPDATE / PS3_VPRM).
192         // ToDo: for the time beeing, the DVD autorun settings are used to determine if the BR should be started automatically.
193         if (name.Equals("BDMV") && bAllowVideo
194         && (bypassSettings || CSettings::Get().GetBool("dvds.autorun")))
195         {
196           CFileItem item(URIUtils::AddFileToFolder(pItem->GetPath(), "index.bdmv"), false);
197           item.SetLabel(g_mediaManager.GetDiskLabel(strDrive));
198           item.GetVideoInfoTag()->m_strFileNameAndPath = g_mediaManager.GetDiskUniqueId(strDrive);
199
200           if (!startFromBeginning && !item.GetVideoInfoTag()->m_strFileNameAndPath.IsEmpty())
201             item.m_lStartOffset = STARTOFFSET_RESUME;
202
203           g_application.PlayFile(item, false);
204           bPlaying = true;
205           return true;
206         }
207
208         // Check if the current foldername indicates a HD DVD structure (default is "HVDVD_TS").
209         // Most HD DVD will also include an "ADV_OBJ" folder for advanced content. This folder should be handled first.
210         // ToDo: for the time beeing, the DVD autorun settings are used to determine if the HD DVD should be started automatically.
211         CFileItemList items, sitems;
212         
213         // Advanced Content HD DVD (most discs?)
214         if (name.Equals("ADV_OBJ"))
215         {
216           CLog::Log(LOGINFO,"HD DVD: Checking for playlist.");
217           // find playlist file
218           CDirectory::GetDirectory(pItem->GetPath(), items, "*.xpl");
219           if (items.Size())
220           {
221             // HD DVD Standard says the highest numbered playlist has to be handled first.
222             CLog::Log(LOGINFO,"HD DVD: Playlist found. Set filetypes to *.xpl for external player.");
223             items.Sort(SortByLabel, SortOrderDescending);
224             phddvdItem = pItem; 
225             hddvdname = URIUtils::GetFileName(items[0]->GetPath());
226             CLog::Log(LOGINFO,"HD DVD: %s", items[0]->GetPath().c_str());
227           }
228         }
229
230         // Standard Content HD DVD (few discs?)
231         if (name.Equals("HVDVD_TS") && bAllowVideo
232         && (bypassSettings || CSettings::Get().GetBool("dvds.autorun")))
233         {
234           if (hddvdname == "")
235           {
236             CLog::Log(LOGINFO,"HD DVD: Checking for ifo.");
237             // find Video Manager or Title Set Information
238             CDirectory::GetDirectory(pItem->GetPath(), items, "HV*.ifo");
239             if (items.Size())
240             {
241               // HD DVD Standard says the lowest numbered ifo has to be handled first.
242               CLog::Log(LOGINFO,"HD DVD: IFO found. Set filename to HV* and filetypes to *.ifo for external player.");
243               items.Sort(SortByLabel, SortOrderAscending);
244               phddvdItem = pItem; 
245               hddvdname = URIUtils::GetFileName(items[0]->GetPath());
246               CLog::Log(LOGINFO,"HD DVD: %s",items[0]->GetPath().c_str());
247             }
248           }
249           // Find and sort *.evo files for internal playback.
250           // While this algorithm works for all of my HD DVDs, it may fail on other discs. If there are very large extras which are
251           // alphabetically before the main movie they will be sorted to the top of the playlist and get played first.
252           CDirectory::GetDirectory(pItem->GetPath(), items, "*.evo");
253           if (items.Size())
254           {
255             // Sort *.evo files in alphabetical order.
256             items.Sort(SortByLabel, SortOrderAscending);
257             int64_t asize = 0;
258             int ecount = 0;
259             // calculate average size of elements above 1gb
260             for (int j = 0; j < items.Size(); j++)
261               if (items[j]->m_dwSize > 1000000000)
262               {
263                 ecount++;
264                 asize = asize + items[j]->m_dwSize;
265               }
266             asize = asize / ecount;
267             // Put largest files in alphabetical order to top of new list.
268             for (int j = 0; j < items.Size(); j++)
269               if (items[j]->m_dwSize >= asize)
270                 sitems.Add (items[j]);
271             // Sort *.evo files by size.
272             items.Sort(SortBySize, SortOrderDescending);
273             // Add other files with descending size to bottom of new list.
274             for (int j = 0; j < items.Size(); j++)
275               if (items[j]->m_dwSize < asize)
276                 sitems.Add (items[j]);
277             // Replace list with optimized list.
278             items.Clear();
279             items.Copy (sitems);
280             sitems.Clear();
281           }
282           if (hddvdname != "")
283           {
284             CFileItem item(URIUtils::AddFileToFolder(phddvdItem->GetPath(), hddvdname), false);
285             item.SetLabel(g_mediaManager.GetDiskLabel(strDrive));
286             item.GetVideoInfoTag()->m_strFileNameAndPath = g_mediaManager.GetDiskUniqueId(strDrive);
287
288             if (!startFromBeginning && !item.GetVideoInfoTag()->m_strFileNameAndPath.IsEmpty())
289             item.m_lStartOffset = STARTOFFSET_RESUME;
290
291             // get playername
292             CStdString hddvdplayer = CPlayerCoreFactory::Get().GetPlayerName(CPlayerCoreFactory::Get().GetDefaultPlayer(item));
293             
294             // Single *.xpl or *.ifo files require an external player to handle playback.
295             // If no matching rule was found, DVDPlayer will be default player.
296             if (hddvdplayer != "DVDPlayer")
297             {
298               CLog::Log(LOGINFO,"HD DVD: External singlefile playback initiated: %s",hddvdname.c_str());
299               g_application.PlayFile(item, false);
300               bPlaying = true;
301               return true;
302             } else
303               CLog::Log(LOGINFO,"HD DVD: No external player found. Fallback to internal one.");
304           }
305
306           //  internal *.evo playback.
307           CLog::Log(LOGINFO,"HD DVD: Internal multifile playback initiated.");
308           g_playlistPlayer.ClearPlaylist(PLAYLIST_VIDEO);
309           g_playlistPlayer.SetShuffle (PLAYLIST_VIDEO, false);
310           g_playlistPlayer.Add(PLAYLIST_VIDEO, items);
311           g_playlistPlayer.SetCurrentPlaylist(PLAYLIST_VIDEO);
312           g_playlistPlayer.Play(0);
313           bPlaying = true;
314           return true;
315         }
316                                 
317         // Video CDs can have multiple file formats. First we need to determine which one is used on the CD
318         CStdString strExt;
319         if (name.Equals("MPEGAV"))
320           strExt = ".dat";
321         if (name.Equals("MPEG2"))
322           strExt = ".mpg";
323
324         // If a file format was extracted we are sure this is a VCD. Autoplay if settings indicate we should.
325         if (!strExt.IsEmpty() && bAllowVideo
326              && (bypassSettings || CSettings::Get().GetBool("dvds.autorun")))
327         {
328           CFileItemList items;
329           CDirectory::GetDirectory(pItem->GetPath(), items, strExt);
330           if (items.Size())
331           {
332             items.Sort(SortByLabel, SortOrderAscending);
333             g_playlistPlayer.ClearPlaylist(PLAYLIST_VIDEO);
334             g_playlistPlayer.Add(PLAYLIST_VIDEO, items);
335             g_playlistPlayer.SetCurrentPlaylist(PLAYLIST_VIDEO);
336             g_playlistPlayer.Play(0);
337             bPlaying = true;
338             return true;
339           }
340         }
341         /* Probably want this if/when we add some automedia action dialog...
342         else if (pItem->GetPath().Find("PICTURES") != -1 && bAllowPictures
343               && (bypassSettings))
344         {
345           bPlaying = true;
346           CStdString strExec;
347           strExec.Format("XBMC.RecursiveSlideShow(%s)", pItem->GetPath().c_str());
348           CBuiltins::Execute(strExec);
349           return true;
350         }
351         */
352       }
353     }
354   }
355
356   // check video first
357   if (!nAddedToPlaylist && !bPlaying && (bypassSettings || CSettings::Get().GetBool("dvds.autorun")))
358   {
359     // stack video files
360     CFileItemList tempItems;
361     tempItems.Append(vecItems);
362     if (CSettings::Get().GetBool("myvideos.stackvideos"))
363       tempItems.Stack();
364     CFileItemList itemlist;
365
366     for (int i = 0; i < tempItems.Size(); i++)
367     {
368       CFileItemPtr pItem = tempItems[i];
369       if (!pItem->m_bIsFolder && pItem->IsVideo())
370       {
371         bPlaying = true;
372         if (pItem->IsStack())
373         {
374           // TODO: remove this once the app/player is capable of handling stacks immediately
375           CStackDirectory dir;
376           CFileItemList items;
377           dir.GetDirectory(pItem->GetPath(), items);
378           itemlist.Append(items);
379         }
380         else
381           itemlist.Add(pItem);
382       }
383     }
384     if (itemlist.Size())
385     {
386       if (!bAllowVideo)
387       {
388         if (!bypassSettings)
389           return false;
390
391         if (g_windowManager.GetActiveWindow() != WINDOW_VIDEO_FILES)
392           if (!g_passwordManager.IsMasterLockUnlocked(true))
393             return false;
394       }
395       g_playlistPlayer.ClearPlaylist(PLAYLIST_VIDEO);
396       g_playlistPlayer.Add(PLAYLIST_VIDEO, itemlist);
397       g_playlistPlayer.SetCurrentPlaylist(PLAYLIST_VIDEO);
398       g_playlistPlayer.Play(0);
399     }
400   }
401   // then music
402   if (!bPlaying && (bypassSettings || CSettings::Get().GetInt("audiocds.autoaction") == AUTOCD_PLAY) && bAllowMusic)
403   {
404     for (int i = 0; i < vecItems.Size(); i++)
405     {
406       CFileItemPtr pItem = vecItems[i];
407       if (!pItem->m_bIsFolder && pItem->IsAudio())
408       {
409         nAddedToPlaylist++;
410         g_playlistPlayer.Add(PLAYLIST_MUSIC, pItem);
411       }
412     }
413   }
414   /* Probably want this if/when we add some automedia action dialog...
415   // and finally pictures
416   if (!nAddedToPlaylist && !bPlaying && bypassSettings && bAllowPictures)
417   {
418     for (int i = 0; i < vecItems.Size(); i++)
419     {
420       CFileItemPtr pItem = vecItems[i];
421       if (!pItem->m_bIsFolder && pItem->IsPicture())
422       {
423         bPlaying = true;
424         CStdString strExec;
425         strExec.Format("XBMC.RecursiveSlideShow(%s)", strDrive.c_str());
426         CBuiltins::Execute(strExec);
427         break;
428       }
429     }
430   }
431   */
432
433   // check subdirs if we are not playing yet
434   if (!bPlaying)
435   {
436     for (int i = 0; i < vecItems.Size(); i++)
437     {
438       CFileItemPtr  pItem = vecItems[i];
439       if (pItem->m_bIsFolder)
440       {
441         if (pItem->GetPath() != "." && pItem->GetPath() != ".." )
442         {
443           if (RunDisc(pDir, pItem->GetPath(), nAddedToPlaylist, false, bypassSettings, startFromBeginning))
444           {
445             bPlaying = true;
446             break;
447           }
448         }
449       } // if (non system) folder
450     } // for all items in directory
451   } // if root folder
452
453   return bPlaying;
454 }
455
456 void CAutorun::HandleAutorun()
457 {
458 #ifndef TARGET_WINDOWS
459   if (!m_bEnable)
460   {
461     CDetectDVDMedia::m_evAutorun.Reset();
462     return ;
463   }
464
465   if (CDetectDVDMedia::m_evAutorun.WaitMSec(0))
466   {
467     ExecuteAutorun();
468     CDetectDVDMedia::m_evAutorun.Reset();
469   }
470 #endif
471 }
472
473 void CAutorun::Enable()
474 {
475   m_bEnable = true;
476 }
477
478 void CAutorun::Disable()
479 {
480   m_bEnable = false;
481 }
482
483 bool CAutorun::IsEnabled() const
484 {
485   return m_bEnable;
486 }
487
488 bool CAutorun::PlayDiscAskResume(const CStdString& path)
489 {
490   return PlayDisc(path, true, !CanResumePlayDVD(path) || CGUIDialogYesNo::ShowAndGetInput(341, -1, -1, -1, 13404, 12021));
491 }
492
493 bool CAutorun::CanResumePlayDVD(const CStdString& path)
494 {
495   CStdString strUniqueId = g_mediaManager.GetDiskUniqueId(path);
496   if (!strUniqueId.IsEmpty())
497   {
498     CVideoDatabase dbs;
499     dbs.Open();
500     CBookmark bookmark;
501     if (dbs.GetResumeBookMark(strUniqueId, bookmark))
502       return true;
503   }
504   return false;
505 }
506
507 void CAutorun::SettingOptionAudioCdActionsFiller(const CSetting *setting, std::vector< std::pair<std::string, int> > &list, int &current)
508 {
509   list.push_back(make_pair(g_localizeStrings.Get(16018), AUTOCD_NONE));
510   list.push_back(make_pair(g_localizeStrings.Get(14098), AUTOCD_PLAY));
511 #ifdef HAS_CDDA_RIPPER
512   list.push_back(make_pair(g_localizeStrings.Get(14096), AUTOCD_RIP));
513 #endif
514 }
515
516 void CAutorun::SettingOptionAudioCdEncodersFiller(const CSetting *setting, std::vector< std::pair<std::string, int> > &list, int &current)
517 {
518 #ifdef HAVE_LIBMP3LAME
519   list.push_back(make_pair(g_localizeStrings.Get(34000), CDDARIP_ENCODER_LAME));
520 #endif
521 #ifdef HAVE_LIBVORBISENC
522   list.push_back(make_pair(g_localizeStrings.Get(34001), CDDARIP_ENCODER_VORBIS));
523 #endif
524   list.push_back(make_pair(g_localizeStrings.Get(34002), CDDARIP_ENCODER_WAV));
525   list.push_back(make_pair(g_localizeStrings.Get(34005), CDDARIP_ENCODER_FLAC));
526   list.push_back(make_pair(g_localizeStrings.Get(34006), CDDARIP_ENCODER_FFMPEG_M4A));
527   list.push_back(make_pair(g_localizeStrings.Get(34007), CDDARIP_ENCODER_FFMPEG_WMA));
528 }
529
530 #endif