private async void TryFillLyrics(TrackInfo track, TrackMediaMetadata meta) { if (string.IsNullOrEmpty(meta.Lyrics) && EnvironmentHelper.HasInternetConnection(!_metadataConfiguration.UpdateLyricsEvenByteBasis)) await TryFillFromMoeAtHome(track, meta); if (string.IsNullOrEmpty(meta.Lyrics) && EnvironmentHelper.HasInternetConnection(!_metadataConfiguration.UpdateLyricsEvenByteBasis)) await TryFillFromGeciMe(track, meta); }
internal void Track(List<double> plasmaVols, int sliceIndex) { //trackInfos.Add( new TrackInfo(srcBarcodes[sam)) int indexInList = 0; foreach (var vol in plasmaVols) { string dstBarcode = correspondingbarcodes[sampleIndex + indexInList][sliceIndex]; if(!IsValidBarcode(dstBarcode)) { throw new Exception(string.Format("第{0}个样品对应的第{1}份目标条码:{2}非法!", sampleIndex + indexInList + 1, sliceIndex + 1,dstBarcode)); } var adjustVol = Math.Min(pipettingSettings.maxVolumePerSlice, vol); var patient = patientInfos[sampleIndex+ indexInList]; string description = GlobalVars.Instance.BloodDescription; TrackInfo info = new TrackInfo(patient.id, dstBarcode, description, Math.Round(adjustVol, 2).ToString(), barcode_plateBarcodes[dstBarcode], barcode_Position[dstBarcode],patient.name); trackInfos.Add(info); indexInList++; } if(sliceIndex+1 == pipettingSettings.dstPlasmaSlice ) { //add buffy info if ( pipettingSettings.dstbuffySlice > 0) { double vol = pipettingSettings.buffyVolume / pipettingSettings.dstbuffySlice; for (indexInList = 0; indexInList < plasmaVols.Count; indexInList++) { var patient = patientInfos[sampleIndex + indexInList]; for (int i = 0; i < pipettingSettings.dstbuffySlice; i++) { if(sampleIndex + indexInList >= correspondingbarcodes.Count ) { throw new Exception(string.Format("cannot find the corresponding barcode for sample:{0}", sampleIndex + indexInList)); } if(pipettingSettings.dstPlasmaSlice + i >= correspondingbarcodes[sampleIndex + indexInList].Count) { throw new Exception(string.Format("cannot find the corresponding barcode for sample:{0}, slice:{1}", sampleIndex + indexInList, pipettingSettings.dstPlasmaSlice + i)); } var dstBarcode = correspondingbarcodes[sampleIndex+indexInList][pipettingSettings.dstPlasmaSlice + i]; TrackInfo info = new TrackInfo(patient.id, dstBarcode, buffyName, Math.Round(vol, 2).ToString(), barcode_plateBarcodes[dstBarcode], barcode_Position[dstBarcode],patient.name); trackInfos.Add(info); } } } sampleIndex += plasmaVols.Count; } }
public TrackInfo PickATrack(TrackInfo excludedInfo) { float r = Random.value; float p = 0; float totalWeight = 0; foreach (TrackInfo info in tracks) { if (info != excludedInfo) totalWeight += info.weight; } if (totalWeight == 0) return PickATrack(null); foreach (TrackInfo info in tracks) { if (info == excludedInfo) continue; float probability = info.weight / totalWeight; p += probability; // Debug.Log(r + " "+ p +" "+ info + " " + info.weight + " " + totalWeight); if (r < p) { return info; } } DebugAux.Assert(false, "Found no track to play!?"); return null; }
public static bool TryParsePath(this string path, out TrackInfo trackInfo) { try { foreach (var regex in _invalidPathRegexes) { var match = regex.Match(path); if (match.Success) { trackInfo = new TrackInfo { Folder = match.Groups["folder"].Value, Artist = match.Groups["artist"].Value, Year = match.Groups["year"].Value, Album = match.Groups["album"].Value, Number = match.Groups["no"].Value, Name = match.Groups["track"].Value }; return true; } } trackInfo = null; return false; } catch { trackInfo = null; return false; } }
public override void SetLastTrack (TrackInfo track) { var dbtrack = track as DatabaseTrackInfo; if (dbtrack != null && dbtrack.AlbumId != album_id) { album_id = dbtrack.AlbumId; } }
public void ClearLocalLyricsPath(TrackInfo track) { try { _provider.ClearLocalLyricsPath(track); } catch { } }
TrackInfo GetTrack(int session, int track) { var ti = new TrackInfo(); var toc_track = DiscHopper.CurrentDisc.ReadTOC().Sessions[session].Tracks[track]; ti.TrackType = toc_track.TrackType; ti.length_lba = toc_track.length_aba; return ti; }
public void NextStep(TrackInfo trackInfo) { float duration = trackInfo.track.Play(); TrackInfo nextTrack = PickATrack(trackInfo); duration += nextTrack.startTime; Debug.Log("[AudioPlayerAdvanced] Starting track, " + duration + " seconds until next."); StartCoroutine(MakeNextDecisionIn(duration, nextTrack)); }
public void SetLocalLyrics(TrackInfo track, IStorageFile storageFile) { try { StorageApplicationPermissions.FutureAccessList.Add(storageFile); _provider.SetLocalLyricsPath(track, storageFile.Path); } catch { } }
public override void SetLastTrack (TrackInfo track) { var dbtrack = track as DatabaseTrackInfo; if (dbtrack != null) { var new_id = dbtrack.Album.ArtistId; if (new_id != id) { id = new_id; } } }
public async Task<IStorageFile> TryGetLocalLyrics(TrackInfo track) { try { var path = _provider.TryGetLocalLyricsPath(track); if (!string.IsNullOrEmpty(path)) return await StorageFile.GetFileFromPathAsync(path); } catch { } return null; }
private async Task TryLoadLyricsFromLocal(TrackInfo track, TrackMediaMetadata meta) { if (_localLyricsService != null) { var file = await _localLyricsService.TryGetLocalLyrics(track); if (file != null) { try { meta.Lyrics = await FileIO.ReadTextAsync(file); } catch { } } } }
public async Task<ITrackMediaMetadata> GetMetadata(TrackInfo track) { var meta = TrackMediaMetadata.Default(); await TryLoadLyricsFromLocal(track, meta); await TryFillFromTrack(track, meta); if (meta.Cover == null) await TryLoadCoverFromCache(track, meta); if (string.IsNullOrEmpty(meta.Lyrics)) await TryLoadLyricsFromCache(track, meta); if (meta.Cover == null && EnvironmentHelper.HasInternetConnection(!_metadataConfiguration.UpdateAlbumCoverEvenByteBasis)) TryFillFromLastFm(track, meta).Ignore(); if (string.IsNullOrEmpty(meta.Lyrics) && EnvironmentHelper.HasInternetConnection(!_metadataConfiguration.UpdateLyricsEvenByteBasis)) TryFillLyrics(track, meta); return meta; }
public void SetCurrentTrack(TrackInfo value) { var updater = _smtc.DisplayUpdater; var musicProp = updater.MusicProperties; if (value != null) { musicProp.Title = value.Title; musicProp.Artist = value.Artist; musicProp.AlbumTitle = value.Album; musicProp.AlbumArtist = value.AlbumArtist; } else { updater.ClearAll(); PlaybackStatus = MediaPlaybackStatus.Closed; } updater.Update(); }
private string GetTrackPath(TrackInfo track, string ext) { string file_path = null; if (track.HasAttribute(TrackMediaAttributes.Podcast)) { string album = FileNamePattern.Escape(track.DisplayAlbumTitle); string title = FileNamePattern.Escape(track.DisplayTrackTitle); file_path = System.IO.Path.Combine("Podcasts", album); file_path = System.IO.Path.Combine(file_path, title); } else if (track.HasAttribute(TrackMediaAttributes.VideoStream)) { string album = FileNamePattern.Escape(track.DisplayAlbumTitle); string title = FileNamePattern.Escape(track.DisplayTrackTitle); file_path = System.IO.Path.Combine(album, title); } else if (ms_device == null || !ms_device.GetTrackPath(track, out file_path)) { // If the folder_depth property exists, we have to put the files in a hiearchy of // the exact given depth (not including the mount point/audio_folder). if (FolderDepth != -1) { int depth = FolderDepth; string album_artist = FileNamePattern.Escape(track.DisplayAlbumArtistName); string track_album = FileNamePattern.Escape(track.DisplayAlbumTitle); string track_number = FileNamePattern.Escape(String.Format("{0:00}", track.TrackNumber)); string track_title = FileNamePattern.Escape(track.DisplayTrackTitle); if (depth == 0) { // Artist - Album - 01 - Title string track_artist = FileNamePattern.Escape(track.DisplayArtistName); file_path = String.Format("{0} - {1} - {2} - {3}", track_artist, track_album, track_number, track_title); } else if (depth == 1) { // Artist - Album/01 - Title file_path = String.Format("{0} - {1}", album_artist, track_album); file_path = System.IO.Path.Combine(file_path, String.Format("{0} - {1}", track_number, track_title)); } else if (depth == 2) { // Artist/Album/01 - Title file_path = album_artist; file_path = System.IO.Path.Combine(file_path, track_album); file_path = System.IO.Path.Combine(file_path, String.Format("{0} - {1}", track_number, track_title)); } else { // If the *required* depth is more than 2..go nuts! for (int i = 0; i < depth - 2; i++) { if (i == 0) { file_path = album_artist.Substring(0, Math.Min(i + 1, album_artist.Length)).Trim(); } else { file_path = System.IO.Path.Combine(file_path, album_artist.Substring(0, Math.Min(i + 1, album_artist.Length)).Trim()); } } // Finally add on the Artist/Album/01 - Track file_path = System.IO.Path.Combine(file_path, album_artist); file_path = System.IO.Path.Combine(file_path, track_album); file_path = System.IO.Path.Combine(file_path, String.Format("{0} - {1}", track_number, track_title)); } } else { file_path = MusicLibrarySource.MusicFileNamePattern.CreateFromTrackInfo(track); } } if (track.HasAttribute(TrackMediaAttributes.VideoStream)) { file_path = System.IO.Path.Combine(WritePathVideo, file_path); } else { file_path = System.IO.Path.Combine(WritePath, file_path); } file_path += ext; return(file_path); }
public static void TrackInfoMerge(TrackInfo track, TagLib.File file, bool preferTrackInfo) { TrackInfoMerge(track, file, preferTrackInfo, false); }
public static void TrackInfoMerge(TrackInfo track, StreamTag tag) { try { switch (tag.Name) { case CommonTags.Artist: track.ArtistName = Choose((string)tag.Value, track.ArtistName); break; case CommonTags.ArtistSortName: case CommonTags.MusicBrainzSortName: track.ArtistNameSort = Choose((string)tag.Value, track.ArtistNameSort); break; case CommonTags.Title: //track.TrackTitle = Choose ((string)tag.Value, track.TrackTitle); string title = Choose((string)tag.Value, track.TrackTitle); // Try our best to figure out common patterns in poor radio metadata. // Often only one tag is sent on track changes inside the stream, // which is title, and usually contains artist and track title, separated // with a " - " string. if (track.IsLive && title.Contains(" - ")) { string [] parts = Regex.Split(title, " - "); track.TrackTitle = parts[1].Trim(); track.ArtistName = parts[0].Trim(); // Often, the title portion contains a postfix with more information // that will confuse lookups, such as "Talk [Studio Version]". // Strip out the [] part. Match match = Regex.Match(track.TrackTitle, "^(.+)[ ]+\\[.*\\]$"); if (match.Groups.Count == 2) { track.TrackTitle = match.Groups[1].Value; } } else { track.TrackTitle = title; } break; case CommonTags.TitleSortName: track.TrackTitleSort = Choose((string)tag.Value, track.TrackTitleSort); break; case CommonTags.Album: track.AlbumTitle = Choose((string)tag.Value, track.AlbumTitle); break; case CommonTags.AlbumSortName: track.AlbumTitleSort = Choose((string)tag.Value, track.AlbumTitleSort); break; case CommonTags.Disc: case CommonTags.AlbumDiscNumber: int disc = (int)tag.Value; track.DiscNumber = disc == 0 ? track.DiscNumber : disc; break; case CommonTags.AlbumDiscCount: int count = (int)tag.Value; track.DiscCount = count == 0 ? track.DiscCount : count; break; case CommonTags.Genre: track.Genre = Choose((string)tag.Value, track.Genre); break; case CommonTags.Composer: track.Composer = Choose((string)tag.Value, track.Composer); break; case CommonTags.Copyright: track.Copyright = Choose((string)tag.Value, track.Copyright); break; case CommonTags.LicenseUri: track.LicenseUri = Choose((string)tag.Value, track.LicenseUri); break; case CommonTags.Comment: track.Comment = Choose((string)tag.Value, track.Comment); break; case CommonTags.TrackNumber: int track_number = (int)tag.Value; track.TrackNumber = track_number == 0 ? track.TrackNumber : track_number; break; case CommonTags.TrackCount: track.TrackCount = (int)tag.Value; break; case CommonTags.BeatsPerMinute: track.Bpm = (int)tag.Value; break; case CommonTags.Duration: if (tag.Value is TimeSpan) { track.Duration = (TimeSpan)tag.Value; } else { track.Duration = new TimeSpan((uint)tag.Value * TimeSpan.TicksPerMillisecond); } break; case CommonTags.MoreInfoUri: track.MoreInfoUri = (SafeUri)tag.Value; break; /* No year tag in GST it seems * case CommonTags.Year: * track.Year = (uint)tag.Value; * break;*/ case CommonTags.NominalBitrate: track.BitRate = (int)tag.Value; break; case CommonTags.StreamType: track.MimeType = (string)tag.Value; break; case CommonTags.VideoCodec: if (tag.Value != null) { track.MediaAttributes |= TrackMediaAttributes.VideoStream; } break; /*case CommonTags.AlbumCoverId: * foreach(string ext in TrackInfo.CoverExtensions) { * string path = Paths.GetCoverArtPath((string) tag.Value, "." + ext); * if(System.IO.File.Exists(path)) { * track.CoverArtFileName = path; * break; * } * } * break;*/ } } catch { } }
private void QueuePlayTrack() { changing_to_track = CurrentTrack; player_engine.OpenPlay(CurrentTrack); }
public int IndexOfFirst(TrackInfo track) { lock (this) { return IndexOf (cache.GetSingleWhere ("AND MetadataHash = ? ORDER BY OrderID", track.MetadataHash)); } }
public string BuildFull(string base_dir, TrackInfo track) { return(BuildFull(base_dir, track, Path.GetExtension(track.Uri.ToString()))); }
public async Task <TrackInfo> GetTrackEventsAsync(string requestString) { var stream = await _httpClient.GetStreamAsync($"?API=TrackV2&XML={requestString}"); return(await TrackInfo.LoadAsync(stream)); }
/// <summary> /// Get the album information from the iTunes track nodes, and add a new album if it does not exist yet. /// </summary> /// <param name="trackInfo">Parsed iTunes track info.</param> /// <param name="ds">ChinookDataSet to be populated.</param> /// <returns>Returns the AlbumId.</returns> private static int AddAlbum(TrackInfo trackInfo, ChinookDataSet ds) { DataRow[] results = ds.Album.Select("Title = '" + trackInfo.AlbumName.Replace("'", "''") + "'"); if (results == null || results.Length == 0) { var row = ds.Album.AddAlbumRow(trackInfo.AlbumName, trackInfo.ArtistId); return row.AlbumId; } return (int)results[0][0]; }
/// <summary> /// Returns a cover art image for the specified track. /// </summary> /// <param name="trackInfo"> /// An object contating data of currently playing track. /// </param> /// <param name="concreteRule"> /// A rule that should be used to search for cover art image. /// </param> /// <returns>Result of cover art image search.</returns> public Bitmap GetBitmap(TrackInfo trackInfo, FindRule concreteRule) { Bitmap result = null; try { if (!trackInfo.IsStream) { var n = new LastFmLib.API20.Album.AlbumGetInfo(trackInfo.Artist, trackInfo.Album); n.Start(); if (n.Succeeded) { if (n.Result.HasAnyImage) { result = n.Result.DownloadImage(LastFmLib.API20.modEnums.ImageSize.Original); if (result == null) { if (n.Result.ImageExtraLarge != null) result = n.Result.DownloadImage(LastFmLib.API20.modEnums.ImageSize.ExtraLarge); else if (n.Result.ImageLarge != null) result = n.Result.DownloadImage(LastFmLib.API20.modEnums.ImageSize.Large); else if (n.Result.ImageMedium != null) result = n.Result.DownloadImage(LastFmLib.API20.modEnums.ImageSize.Medium); else if (n.Result.ImageSmall != null) result = n.Result.DownloadImage(LastFmLib.API20.modEnums.ImageSize.Small); } } } } else { // get bitmap for radio String[] s = String.IsNullOrEmpty(trackInfo.Artist) ? trackInfo.Title.Split('-') : new string[] { trackInfo.Artist, trackInfo.Title }; if (s.Length > 1) { var n = new LastFmLib.API20.Tracks.TrackGetInfo(s[0].Trim(), s[1].Trim()); n.Start(); if (n.Succeeded) { var info = (TrackInformation)n.Result; if (info.Album != null && info.Album.HasAnyImage) { result = info.Album.DownloadImage(LastFmLib.API20.modEnums.ImageSize.Original); if (result == null) { if (info.Album.ImageExtraLarge != null) result = info.Album.DownloadImage(LastFmLib.API20.modEnums.ImageSize.ExtraLarge); else if (info.Album.ImageLarge != null) result = info.Album.DownloadImage(LastFmLib.API20.modEnums.ImageSize.Large); else if (n.Result.ImageMedium != null) result = info.Album.DownloadImage(LastFmLib.API20.modEnums.ImageSize.Medium); else if (n.Result.ImageSmall != null) result = info.Album.DownloadImage(LastFmLib.API20.modEnums.ImageSize.Small); } } } } } } catch (Exception ex) { #if DEBUG MessageBox.Show(ex.ToString(), "LastFm Error", MessageBoxButton.OK, MessageBoxImage.Error); #endif } return result; }
/// <summary> /// Parses a track node of iTunes library. /// </summary> /// <param name="trackInfo">Parsed iTunes track info.</param> /// <param name="iterator">Iterator over iTunes track info nodes.</param> /// <returns>Returns false if this track should not be parsed, returns true otherwise.</returns> private static bool ParseTrackNode(TrackInfo trackInfo, XPathNodeIterator iterator) { while (iterator.MoveNext()) { switch (iterator.Current.Value) { case "Artist": trackInfo.ArtistName = GetNextString(iterator); break; case "Album": trackInfo.AlbumName = GetNextString(iterator); break; case "Genre": trackInfo.GenreName = GetNextString(iterator); break; case "Kind": trackInfo.MediaTypeName = GetNextString(iterator); break; case "Name": trackInfo.Name = GetNextString(iterator); break; case "Composer": trackInfo.Composer = GetNextString(iterator); break; case "Track ID": trackInfo.OriginalTrackId = GetNextInteger(iterator); break; case "Size": trackInfo.Size = GetNextInteger(iterator); break; case "Total Time": trackInfo.Time = GetNextInteger(iterator); break; case "TV Show": trackInfo.UnitPrice = (decimal) 1.99; break; case "Movie": trackInfo.UnitPrice = (decimal) 9.99; break; case "Podcast": return false; default: break; } } return true; }
/// <summary> /// Import media track information from iTunes library file. /// </summary> /// <param name="ds">ChinookDataSet to be populated.</param> /// <param name="navigator">XPath navigator of iTunes library.</param> private void ImportTracks(ChinookDataSet ds, XPathNavigator navigator) { var trackInfo = new TrackInfo(); // Creates an XPath to the track info nodes. var nodes = navigator.Select("/plist/dict/dict/dict"); while (nodes.MoveNext()) { trackInfo.Clear(); var clone = nodes.Current.Clone(); var iterator = clone.SelectChildren("", ""); if (ParseTrackNode(trackInfo, iterator)) { trackInfo.ArtistId = AddArtist(trackInfo, ds); trackInfo.AlbumId = AddAlbum(trackInfo, ds); trackInfo.GenreId = AddGenre(trackInfo, ds); trackInfo.MediaTypeId = AddMediaType(trackInfo, ds); // Add a new track to the dataset. ChinookDataSet.TrackRow row = ds.Track.AddTrackRow(trackInfo.Name, trackInfo.AlbumId, trackInfo.MediaTypeId, trackInfo.GenreId, trackInfo.Composer, trackInfo.Time, trackInfo.Size, trackInfo.UnitPrice); // Maps the track ids used by iTunes in order to use it later when importing playlists. _trackIds[trackInfo.OriginalTrackId] = row.TrackId; } } }
/// <summary> /// Get the media type information from the iTunes track nodes, and add a new media type if it does not exist yet. /// </summary> /// <param name="trackInfo">Parsed iTunes track info.</param> /// <param name="ds">ChinookDataSet to be populated.</param> /// <returns>Returns the MediaTypeId.</returns> private static int AddMediaType(TrackInfo trackInfo, ChinookDataSet ds) { DataRow[] results = ds.MediaType.Select("Name = '" + trackInfo.MediaTypeName.Replace("'", "''") + "'"); if (results == null || results.Length == 0) { var row = ds.MediaType.AddMediaTypeRow(trackInfo.MediaTypeName); return row.MediaTypeId; } return (int)results[0][0]; }
public WikipediaArtistQuery(TrackInfo track) { this.track = track; this.Init(); }
private async Task TryLoadCoverFromCache(TrackInfo track, TrackMediaMetadata meta) { var stream = await _albumCoverCache.TryGetCache(track.Album, track.Artist); if (stream != null) meta.Cover = await MediaHelper.CreateImage(stream); }
public TagList(TrackInfo track) : this() { Merge(track); }
private async Task TryFillFromLastFm(TrackInfo track, TrackMediaMetadata meta) { try { var uri = await GetCoverUriFromLastFm(track.Artist, track.Album); if (uri == null) { var trackResp = await _lastfm.Track.GetInfoAsync(track.Title ?? string.Empty, track.Artist ?? string.Empty); if (trackResp.Success) uri = await GetCoverUriFromLastFm(trackResp.Content.ArtistName, trackResp.Content.AlbumName); } if (uri != null) { var stream = await _albumCoverCache.Download(track.Album, track.Artist, uri); if (stream != null) meta.Cover = await MediaHelper.CreateImage(stream); } } catch { } }
private static extern bool criAtomExPlayback_GetPlaybackTrackInfo(uint id, out TrackInfo info);
private async Task TryFillFromTrack(TrackInfo track, TrackMediaMetadata meta) { try { var uri = track.Source; StorageFile file; if (uri.Scheme == "ms-appx") file = await StorageFile.GetFileFromApplicationUriAsync(uri); else if (uri.IsFile) file = await StorageFile.GetFileFromPathAsync(uri.LocalPath); else throw new NotSupportedException("not supported uri."); var provider = await MediaMetadataProvider.CreateFromStream(await file.OpenReadAsync(), uri.ToString(), false); var cover = provider.Pictures.FirstOrDefault(o => o.PictureType.Contains("Cover")); if (cover == null) cover = provider.Pictures.FirstOrDefault(); if (cover != null) { var stream = new MemoryStream(cover.Data); meta.Cover = await MediaHelper.CreateImage(stream.AsRandomAccessStream()); } if (string.IsNullOrEmpty(meta.Lyrics)) meta.Lyrics = provider.Lyrics; } catch { } }
private async Task TryLoadLyricsFromCache(TrackInfo track, TrackMediaMetadata meta) { var text = await _lyricsCache.TryGetCache(track.Title, track.Artist); if (!string.IsNullOrEmpty(text)) meta.Lyrics = text; }
protected virtual int GetIconIndex(TrackInfo track) { int icon_index = -1; if (track.PlaybackError != StreamPlaybackError.None) { icon_index = (int)(track.PlaybackError == StreamPlaybackError.Drm ? Icon.Protected : Icon.Error); } else if (track.IsPlaying) { icon_index = (int)(ServiceManager.PlayerEngine.CurrentState == PlayerState.Paused ? Icon.Paused : Icon.Playing); } else if ((track.MediaAttributes & TrackMediaAttributes.ExternalResource) != 0) { icon_index = (int)Icon.External; } else { icon_index = -1; } return icon_index; }
private void OnPlayerEvent(PlayerEventArgs args) { switch (args.Event) { case PlayerEvent.StartOfStream: CurrentTrack = player_engine.CurrentTrack; consecutive_errors = 0; break; case PlayerEvent.EndOfStream: EosTransition(); break; case PlayerEvent.Error: if (++consecutive_errors >= 5) { consecutive_errors = 0; player_engine.Close(false); OnStopped(); break; } CancelErrorTransition(); // TODO why is this so long? any reason not to be instantaneous? error_transition_id = Application.RunTimeout(250, delegate { EosTransition(); RequestTrackHandler(); return(true); }); break; case PlayerEvent.StateChange: if (((PlayerEventStateChangeArgs)args).Current != PlayerState.Loading) { break; } TrackInfo track = player_engine.CurrentTrack; if (changing_to_track != track && track != null) { CurrentTrack = track; } changing_to_track = null; if (!raise_started_after_transition) { transition_track_started = false; OnTrackStarted(); } else { transition_track_started = true; } break; case PlayerEvent.RequestNextTrack: RequestTrackHandler(); break; } }
private void OnError(IntPtr player, uint domain, int code, IntPtr error, IntPtr debug) { TrackInfo failed_track = CurrentTrack; Close(true); string error_message = error == IntPtr.Zero ? Catalog.GetString("Unknown Error") : GLib.Marshaller.Utf8PtrToString(error); if (domain == GST_RESOURCE_ERROR) { GstResourceError domain_code = (GstResourceError)code; if (failed_track != null) { switch (domain_code) { case GstResourceError.NotFound: failed_track.SavePlaybackError(StreamPlaybackError.ResourceNotFound); break; default: break; } } Log.Error(String.Format("GStreamer resource error: {0}", domain_code), false); } else if (domain == GST_STREAM_ERROR) { GstStreamError domain_code = (GstStreamError)code; if (failed_track != null) { switch (domain_code) { case GstStreamError.CodecNotFound: failed_track.SavePlaybackError(StreamPlaybackError.CodecNotFound); break; default: break; } } Log.Error(String.Format("GStreamer stream error: {0}", domain_code), false); } else if (domain == GST_CORE_ERROR) { GstCoreError domain_code = (GstCoreError)code; if (failed_track != null) { switch (domain_code) { case GstCoreError.MissingPlugin: failed_track.SavePlaybackError(StreamPlaybackError.CodecNotFound); break; default: break; } } if (domain_code != GstCoreError.MissingPlugin) { Log.Error(String.Format("GStreamer core error: {0}", (GstCoreError)code), false); } } else if (domain == GST_LIBRARY_ERROR) { Log.Error(String.Format("GStreamer library error: {0}", (GstLibraryError)code), false); } OnEventChanged(new PlayerEventErrorArgs(error_message)); }
public override int IndexOf(TrackInfo track) { lock (this) { if (track is DatabaseTrackInfo) { return (int) cache.IndexOf (track as DatabaseTrackInfo); } else if (track is Banshee.Streaming.RadioTrackInfo) { return (int) cache.IndexOf ((track as Banshee.Streaming.RadioTrackInfo).ParentTrack as DatabaseTrackInfo); } return -1; } }
private void RenderStage(Cairo.Context cr, TrackInfo track, ImageSurface image) { RenderCoverArt(cr, image); RenderTrackInfo(cr, track, true, true); }
public static void TrackInfoMerge(TrackInfo track, TagLib.File file) { TrackInfoMerge(track, file, false); }
protected virtual string GetFirstLineText(TrackInfo track) { return(String.Format("<b>{0}</b>", GLib.Markup.EscapeText(track.DisplayTrackTitle))); }
public static void TrackInfoMerge(TrackInfo track, TagLib.File file, bool preferTrackInfo, bool import_rating_and_play_count) { // TODO support these as arrays: // Performers[] (track artists), AlbumArtists[], Composers[], Genres[] // Note: this should be kept in sync with the metadata written in SaveTrackMetadataJob.cs if (file != null) { track.Uri = new SafeUri(file.Name); track.MimeType = file.MimeType; track.Duration = file.Properties.Duration; track.BitRate = file.Properties.AudioBitrate; track.SampleRate = file.Properties.AudioSampleRate; track.BitsPerSample = file.Properties.BitsPerSample; FindTrackMediaAttributes(track, file); track.ArtistName = Choose(file.Tag.JoinedPerformers, track.ArtistName, preferTrackInfo); track.ArtistNameSort = Choose(file.Tag.JoinedPerformersSort, track.ArtistNameSort, preferTrackInfo); track.ArtistMusicBrainzId = Choose(file.Tag.MusicBrainzArtistId, track.ArtistMusicBrainzId, preferTrackInfo); track.AlbumTitle = Choose(file.Tag.Album, track.AlbumTitle, preferTrackInfo); track.AlbumTitleSort = Choose(file.Tag.AlbumSort, track.AlbumTitleSort, preferTrackInfo); track.AlbumMusicBrainzId = Choose(file.Tag.MusicBrainzReleaseId, track.AlbumMusicBrainzId, preferTrackInfo); // AlbumArtist cannot be set until the track is marked as a compilation. track.IsCompilation = preferTrackInfo ? track.IsCompilation : IsCompilation(file); track.AlbumArtist = Choose(file.Tag.FirstAlbumArtist, track.AlbumArtist, preferTrackInfo); track.AlbumArtistSort = Choose(file.Tag.FirstAlbumArtistSort, track.AlbumArtistSort, preferTrackInfo); track.TrackTitle = Choose(file.Tag.Title, track.TrackTitle, preferTrackInfo); track.TrackTitleSort = Choose(file.Tag.TitleSort, track.TrackTitleSort, preferTrackInfo); track.MusicBrainzId = Choose(file.Tag.MusicBrainzTrackId, track.MusicBrainzId, preferTrackInfo); track.Genre = Choose(file.Tag.FirstGenre, track.Genre, preferTrackInfo); track.Composer = Choose(file.Tag.FirstComposer, track.Composer, preferTrackInfo); track.Conductor = Choose(file.Tag.Conductor, track.Conductor, preferTrackInfo); track.Grouping = Choose(file.Tag.Grouping, track.Grouping, preferTrackInfo); track.Copyright = Choose(file.Tag.Copyright, track.Copyright, preferTrackInfo); track.Comment = Choose(file.Tag.Comment, track.Comment, preferTrackInfo); track.TrackNumber = Choose((int)file.Tag.Track, track.TrackNumber, preferTrackInfo); track.TrackCount = Choose((int)file.Tag.TrackCount, track.TrackCount, preferTrackInfo); track.DiscNumber = Choose((int)file.Tag.Disc, track.DiscNumber, preferTrackInfo); track.DiscCount = Choose((int)file.Tag.DiscCount, track.DiscCount, preferTrackInfo); track.Year = Choose((int)file.Tag.Year, track.Year, preferTrackInfo); track.Bpm = Choose((int)file.Tag.BeatsPerMinute, track.Bpm, preferTrackInfo); if (import_rating_and_play_count) { int file_rating = 0, file_playcount = 0; StreamRatingTagger.GetRatingAndPlayCount(file, ref file_rating, ref file_playcount); track.Rating = Choose(file_rating, track.Rating, preferTrackInfo); track.PlayCount = Choose(file_playcount, track.PlayCount, preferTrackInfo); } } else { track.MediaAttributes = TrackMediaAttributes.AudioStream; if (track.Uri != null && VideoExtensions.IsMatchingFile(track.Uri.AbsoluteUri)) { track.MediaAttributes |= TrackMediaAttributes.VideoStream; } } track.FileSize = Banshee.IO.File.GetSize(track.Uri); track.FileModifiedStamp = Banshee.IO.File.GetModifiedTime(track.Uri); track.LastSyncedStamp = DateTime.Now; if (String.IsNullOrEmpty(track.TrackTitle)) { try { string filename = System.Web.HttpUtility.UrlDecode (System.IO.Path.GetFileNameWithoutExtension(track.Uri.AbsoluteUri)); if (!String.IsNullOrEmpty(filename)) { track.TrackTitle = filename; } } catch {} } // TODO look for track number in the file name if not set? // TODO could also pull artist/album from folders _iff_ files two levels deep in the MusicLibrary folder // TODO these ideas could also be done in an extension that collects such hacks }
/// <summary> /// /// </summary> /// <param name="fileName"></param> /// <param name="completedCallback">抽取的轨道,不包含重复轨道;重复轨道文件名带有.bak</param> public MediaFile Extract(Action <double, EACProgressType> progressCallback) { if (!new FileInfo(sourceFile).Exists) { return(null); } _progressCallback = progressCallback; state = ProcessState.FetchStream; StartEac($"\"{sourceFile}\"", false); var args = new List <string>(); var extractResult = new List <TrackInfo>(); List <TrackInfo> srcAudio = new List <TrackInfo>(); List <TrackInfo> srcSub = new List <TrackInfo>(); foreach (TrackInfo track in tracks) { switch (track.Type) { case TrackType.Audio: srcAudio.Add(track); break; case TrackType.Subtitle: srcSub.Add(track); break; default: break; } } if (srcAudio.Count != JobAudio.Count) { OKETaskException ex = new OKETaskException(Constants.audioNumMismatchSmr); ex.progress = 0.0; ex.Data["SRC_TRACK"] = srcAudio.Count; ex.Data["DST_TRACK"] = JobAudio.Count; throw ex; } if (srcSub.Count != JobSub.Count) { OKETaskException ex = new OKETaskException(Constants.subNumMismatchSmr); ex.progress = 0.0; ex.Data["SRC_TRACK"] = srcSub.Count; ex.Data["DST_TRACK"] = JobSub.Count; throw ex; } int audioId = 0, subId = 0; foreach (TrackInfo track in tracks) { EacOutputTrackType trackType = s_eacOutputs.Find(val => val.Codec == track.Codec); if (!(trackType.Extract || trackType.Type == TrackType.Video && extractVideo)) { continue; } ; if (track.Type == TrackType.Audio) { AudioInfo jobAudioInfo = JobAudio[audioId++]; if (jobAudioInfo.MuxOption == MuxOption.Skip) { continue; } } if (track.Type == TrackType.Subtitle) { Info jobSubInfo = JobSub[subId++]; if (jobSubInfo.MuxOption == MuxOption.Skip) { continue; } } args.Add($"{track.Index}:\"{track.OutFileName}\""); extractResult.Add(track); } JobAudio.RemoveAll(info => info.MuxOption == MuxOption.Skip); JobSub.RemoveAll(info => info.MuxOption == MuxOption.Skip); state = ProcessState.ExtractStream; StartEac($"\"{sourceFile}\" {string.Join(" ", args)}", true); foreach (TrackInfo track in extractResult) { FileInfo finfo = new FileInfo(track.OutFileName); if (!finfo.Exists || finfo.Length == 0) { throw new Exception("文件输出失败: " + track.OutFileName); } else { track.FileSize = finfo.Length; } if (track.Type == TrackType.Audio) { FFmpegVolumeChecker checker = new FFmpegVolumeChecker(track.OutFileName); checker.start(); checker.waitForFinish(); track.MaxVolume = checker.MaxVolume; track.MeanVolume = checker.MeanVolume; } } List <int> removeList = new List <int>(); for (int i = 0; i < extractResult.Count; i++) { TrackInfo track = extractResult[i]; if (removeList.Contains(track.Index)) { continue; } if (track.IsEmpty()) { Logger.Warn(track.OutFileName + "被检测为空轨道。"); removeList.Add(track.Index); track.MarkSkipping(); continue; } for (int j = i + 1; j < extractResult.Count; j++) { TrackInfo other = extractResult[j]; if (track.IsDuplicate(other)) { Logger.Warn(track.OutFileName + "被检测为与" + other.OutFileName + "重复。"); removeList.Add(other.Index); other.MarkSkipping(); } } } MediaFile mf = new MediaFile(); audioId = 0; subId = 0; foreach (var item in extractResult) { OKEFile file = new OKEFile(item.OutFileName); switch (item.Type) { case TrackType.Audio: AudioInfo audioInfo = JobAudio[audioId++]; audioInfo.DupOrEmpty = item.DupOrEmpty; mf.AddTrack(new AudioTrack(file, audioInfo)); break; case TrackType.Subtitle: Info subInfo = JobSub[subId++]; subInfo.DupOrEmpty = item.DupOrEmpty; mf.AddTrack(new SubtitleTrack(file, subInfo)); break; case TrackType.Chapter: FileInfo txtChapter = new FileInfo(Path.ChangeExtension(sourceFile, ".txt")); if (txtChapter.Exists) { Logger.Info("检测到单独准备的章节,不予添加"); } else { file.Rename(txtChapter.FullName); } break; case TrackType.Video: mf.AddTrack(new VideoTrack(file, new VideoInfo())); break; default: System.Windows.MessageBox.Show(item.OutFileName, "不认识的轨道呢"); break; } } return(mf); }
private async Task CurrentTrackChanged(TrackInfo info) { await UpdateTitle(info); }
private void OnPlayerEvent (Banshee.MediaEngine.PlayerEventArgs args) { last_track = ServiceManager.PlayerEngine.CurrentTrack; }
public bool TryMerge(IDictionary <Guid, IList <MediaItemAspect> > extractedAspects, IDictionary <Guid, IList <MediaItemAspect> > existingAspects) { try { TrackInfo existing = new TrackInfo(); TrackInfo extracted = new TrackInfo(); //Extracted aspects IList <MultipleMediaItemAspect> providerResourceAspects; if (!MediaItemAspect.TryGetAspects(extractedAspects, ProviderResourceAspect.Metadata, out providerResourceAspects)) { return(false); } //Existing aspects IList <MultipleMediaItemAspect> existingProviderResourceAspects; MediaItemAspect.TryGetAspects(existingAspects, ProviderResourceAspect.Metadata, out existingProviderResourceAspects); //Don't merge virtual resources if (!providerResourceAspects.Where(p => p.GetAttributeValue <int>(ProviderResourceAspect.ATTR_TYPE) == ProviderResourceAspect.TYPE_VIRTUAL).Any()) { //Replace if existing is a virtual resource if (existingProviderResourceAspects.Where(p => p.GetAttributeValue <int>(ProviderResourceAspect.ATTR_TYPE) == ProviderResourceAspect.TYPE_VIRTUAL).Any()) { MediaItemAspect.SetAttribute(existingAspects, MediaAspect.ATTR_ISVIRTUAL, false); MediaItemAspect.SetAttribute(existingAspects, MediaAspect.ATTR_ISSTUB, providerResourceAspects.Where(p => p.GetAttributeValue <int>(ProviderResourceAspect.ATTR_TYPE) == ProviderResourceAspect.TYPE_STUB).Any()); existingAspects.Remove(ProviderResourceAspect.ASPECT_ID); foreach (Guid aspect in extractedAspects.Keys) { if (!existingAspects.ContainsKey(aspect)) { existingAspects.Add(aspect, extractedAspects[aspect]); } } } else if (existingProviderResourceAspects.Where(p => p.GetAttributeValue <int>(ProviderResourceAspect.ATTR_TYPE) == ProviderResourceAspect.TYPE_STUB).Any() || providerResourceAspects.Where(p => p.GetAttributeValue <int>(ProviderResourceAspect.ATTR_TYPE) == ProviderResourceAspect.TYPE_STUB).Any()) { MediaItemAspect.SetAttribute(existingAspects, MediaAspect.ATTR_ISVIRTUAL, false); MediaItemAspect.SetAttribute(existingAspects, MediaAspect.ATTR_ISSTUB, true); foreach (Guid aspect in extractedAspects.Keys) { if (!existingAspects.ContainsKey(aspect)) { existingAspects.Add(aspect, extractedAspects[aspect]); } else if (aspect == ProviderResourceAspect.ASPECT_ID) { int newResIndex = 0; foreach (MediaItemAspect mia in existingAspects[aspect]) { if (newResIndex <= mia.GetAttributeValue <int>(ProviderResourceAspect.ATTR_RESOURCE_INDEX)) { newResIndex = mia.GetAttributeValue <int>(ProviderResourceAspect.ATTR_RESOURCE_INDEX) + 1; } } foreach (MediaItemAspect mia in extractedAspects[aspect]) { mia.SetAttribute(ProviderResourceAspect.ATTR_RESOURCE_INDEX, newResIndex); existingAspects[aspect].Add(mia); newResIndex++; } } } } } existing.FromMetadata(existingAspects); extracted.FromMetadata(extractedAspects); existing.MergeWith(extracted, false, false); existing.SetMetadata(existingAspects); return(true); } catch (Exception e) { // Only log at the info level here - And simply return false. This lets the caller know that we // couldn't perform our task here. ServiceRegistration.Get <ILogger>().Info("EpisodeMergeHandler: Exception merging resources (Text: '{0}')", e.Message); return(false); } }
//---------------------------------------------------------------------------------------------------------------------- public TrackInfoViewModel(TrackInfo pTrackInfo) { trackInfo = pTrackInfo; }
/** * <summary>再生トラック情報の取得</summary> * <param name='info'>再生トラック情報</param> * <returns>取得に成功したか</returns> * <remarks> * <para header='説明'>::CriAtomExPlayer::Start 関数で再生されたキューのトラック情報を取得します。<br/> * 取得できるトラック情報はキュー直下の情報だけです、サブシーケンスやキューリンクの情報は取得できません。<br/></para> * <para header='備考'>以下に該当するデータを再生中の場合、トラック情報の取得に失敗します。<br/> * - キュー以外のデータを再生している。(トラック情報が存在しないため)<br/> * - 再生中のキューがポリフォニックタイプ、またはセレクタ参照のスイッチタイプである。 * (トラック情報が複数存在する可能性があるため)<br/> * - 再生中のキューがトラック遷移タイプである。(遷移により再生トラックが変わるため)<br/></para> * </remarks> * <seealso cref='CriAtomExPlayer::Start'/> */ public bool GetTrackInfo(out TrackInfo info) { return(criAtomExPlayback_GetPlaybackTrackInfo(this.id, out info)); }
public void Run() { //params var compiled = IN_CompileJob; var context = compiled.IN_CueContext; OUT_Disc = new Disc(); //generation state int curr_index; int curr_blobIndex = -1; int curr_blobMSF = -1; BlobInfo curr_blobInfo = null; long curr_blobOffset = -1; //mount all input files MountBlobs(); //unhappily, we cannot determine the length of all the tracks without knowing the length of the files //now that the files are mounted, we can figure the track lengths AnalyzeTracks(); //loop from track 1 to 99 //(track 0 isnt handled yet, that's way distant work) for (int t = 1; t < TrackInfos.Count; t++) { TrackInfo ti = TrackInfos[t]; CompiledCueTrack cct = ti.CompiledCueTrack; //--------------------------------- //setup track pregap processing //per "Example 05" on digitalx.org, pregap can come from index specification and pregap command int specifiedPregapLength = cct.PregapLength.Sector; int impliedPregapLength = cct.Indexes[1].FileMSF.Sector - cct.Indexes[0].FileMSF.Sector; int totalPregapLength = specifiedPregapLength + impliedPregapLength; //from now on we'll track relative timestamp and increment it continually int relMSF = -totalPregapLength; //read more at policies declaration //if (!context.DiscMountPolicy.CUE_PauseContradictionModeA) // relMSF += 1; //--------------------------------- //--------------------------------- //generate sectors for this track. //advance to the next file if needed if (curr_blobIndex != cct.BlobIndex) { curr_blobIndex = cct.BlobIndex; curr_blobOffset = 0; curr_blobMSF = 0; curr_blobInfo = BlobInfos[curr_blobIndex]; } //work until the next track is reached, or the end of the current file is reached, depending on the track type curr_index = 0; for (; ;) { bool trackDone = false; bool generateGap = false; if (specifiedPregapLength > 0) { //if burning through a specified pregap, count it down generateGap = true; specifiedPregapLength--; } else { //if burning through the file, select the appropriate index by inspecting the next index and seeing if we've reached it for (; ;) { if (curr_index == cct.Indexes.Count - 1) { break; } if (curr_blobMSF >= cct.Indexes[curr_index + 1].FileMSF.Sector) { curr_index++; if (curr_index == 1) { //WE ARE NOW AT INDEX 1: generate the RawTOCEntry for this track EmitRawTOCEntry(cct); } } else { break; } } } //select the track type for the subQ //it's obviously the same as the main track type usually, but during a pregap it can be different TrackInfo qTrack = ti; int qRelMSF = relMSF; if (curr_index == 0) { //tweak relMSF due to ambiguity/contradiction in yellowbook docs if (!context.DiscMountPolicy.CUE_PregapContradictionModeA) { qRelMSF++; } //[IEC10149] says there's two "intervals" of a pregap. //mednafen's pseudocode interpretation of this: //if this is a data track and the previous track was not data, the last 150 sectors of the pregap match this track and the earlier sectors (at least 75) math the previous track //I agree, so let's do it that way if (t != 1 && cct.TrackType != CueTrackType.Audio && TrackInfos[t - 1].CompiledCueTrack.TrackType == CueTrackType.Audio) { if (relMSF < -150) { qTrack = TrackInfos[t - 1]; } } } //generate the right kind of sector synth for this track SS_Base ss = null; if (generateGap) { var ss_gap = new SS_Gap(); ss_gap.TrackType = qTrack.CompiledCueTrack.TrackType; ss = ss_gap; } else { int sectorSize = int.MaxValue; switch (qTrack.CompiledCueTrack.TrackType) { case CueTrackType.Audio: case CueTrackType.CDI_2352: case CueTrackType.Mode1_2352: case CueTrackType.Mode2_2352: ss = new SS_2352(); sectorSize = 2352; break; case CueTrackType.Mode1_2048: ss = new SS_Mode1_2048(); sectorSize = 2048; break; default: case CueTrackType.Mode2_2336: throw new InvalidOperationException($"Not supported: {cct.TrackType}"); } ss.Blob = curr_blobInfo.Blob; ss.BlobOffset = curr_blobOffset; curr_blobOffset += sectorSize; curr_blobMSF++; } ss.Policy = context.DiscMountPolicy; //setup subQ byte ADR = 1; //absent some kind of policy for how to set it, this is a safe assumption: ss.sq.SetStatus(ADR, (EControlQ)(int)qTrack.CompiledCueTrack.Flags); ss.sq.q_tno = BCD2.FromDecimal(cct.Number); ss.sq.q_index = BCD2.FromDecimal(curr_index); ss.sq.AP_Timestamp = OUT_Disc._Sectors.Count; ss.sq.Timestamp = qRelMSF; //setup subP if (curr_index == 0) { ss.Pause = true; } OUT_Disc._Sectors.Add(ss); relMSF++; if (cct.IsFinalInFile) { //sometimes, break when the file is exhausted if (curr_blobOffset >= curr_blobInfo.Length) { trackDone = true; } } else { //other times, break when the track is done //(this check is safe because it's not the final track overall if it's not the final track in a file) if (curr_blobMSF >= TrackInfos[t + 1].CompiledCueTrack.Indexes[0].FileMSF.Sector) { trackDone = true; } } if (trackDone) { break; } } //--------------------------------- //gen postgap sectors int specifiedPostgapLength = cct.PostgapLength.Sector; for (int s = 0; s < specifiedPostgapLength; s++) { var ss = new SS_Gap(); ss.TrackType = cct.TrackType; //TODO - old track type in some < -150 cases? //-subq- byte ADR = 1; ss.sq.SetStatus(ADR, (EControlQ)(int)cct.Flags); ss.sq.q_tno = BCD2.FromDecimal(cct.Number); ss.sq.q_index = BCD2.FromDecimal(curr_index); ss.sq.AP_Timestamp = OUT_Disc._Sectors.Count; ss.sq.Timestamp = relMSF; //-subP- //always paused--is this good enough? ss.Pause = true; OUT_Disc._Sectors.Add(ss); relMSF++; } } //end track loop //add RawTOCEntries A0 A1 A2 to round out the TOC var TOCMiscInfo = new Synthesize_A0A1A2_Job { IN_FirstRecordedTrackNumber = IN_CompileJob.OUT_CompiledDiscInfo.FirstRecordedTrackNumber, IN_LastRecordedTrackNumber = IN_CompileJob.OUT_CompiledDiscInfo.LastRecordedTrackNumber, IN_Session1Format = IN_CompileJob.OUT_CompiledDiscInfo.SessionFormat, IN_LeadoutTimestamp = OUT_Disc._Sectors.Count }; TOCMiscInfo.Run(OUT_Disc.RawTOCEntries); //TODO - generate leadout, or delegates at least //blech, old crap, maybe //OUT_Disc.Structure.Synthesize_TOCPointsFromSessions(); //FinishLog(); } //Run()
private static bool criAtomExPlayback_GetPlaybackTrackInfo(uint id, out TrackInfo info) { info = new TrackInfo(); return(false); }
public void Enqueue(string path) { try { SafeUri uri = new SafeUri(path); if (uri.IsLocalPath && !String.IsNullOrEmpty(uri.LocalPath)) { path = uri.LocalPath; } } catch { } lock (this) { if (importer == null) { importer = new DatabaseImportManager(this); importer.KeepUserJobHidden = true; importer.ImportResult += delegate(object o, DatabaseImportResultArgs args) { Banshee.ServiceStack.Application.Invoke(delegate { if (args.Error != null || path_to_play != null) { return; } path_to_play = args.Path; if (args.Track == null) { // Play immediately if the track is already in the source, // otherwise the call will be deferred until the track has // been imported and loaded into the cache PlayEnqueued(); } }); }; importer.Finished += delegate { if (visible) { Banshee.Base.ThreadAssist.ProxyToMain(delegate { TrackInfo current_track = ServiceManager.PlaybackController.CurrentTrack; // Don't switch to FSQ if the current item is a video if (current_track == null || !current_track.HasAttribute(TrackMediaAttributes.VideoStream)) { ServiceManager.SourceManager.SetActiveSource(this); } }); } }; } if (PlaylistFileUtil.PathHasPlaylistExtension(path)) { Banshee.Kernel.Scheduler.Schedule(new DelegateJob(delegate { // If it's in /tmp it probably came from Firefox - just play it if (path.StartsWith(Paths.SystemTempDir)) { Banshee.Streaming.RadioTrackInfo.OpenPlay(path); } else { PlaylistFileUtil.ImportPlaylistToLibrary(path, this, importer); } })); } else { importer.Enqueue(path); } } }
public HttpResponseMessage UpdateTrack(TrackInfo track) { try { var updatesToProcess = false; var originalTrack = TrackDataAccess.GetItem(track.TrackId, track.CodeCampId); if (!string.Equals(track.Title, originalTrack.Title)) { originalTrack.Title = track.Title; updatesToProcess = true; } if (!string.Equals(track.Description, originalTrack.Description)) { originalTrack.Description = track.Description; updatesToProcess = true; } if (originalTrack.CustomProperties != null) { // parse custom properties for updates foreach (var property in originalTrack.CustomPropertiesObj) { if (track.CustomPropertiesObj.Any(p => p.Name == property.Name)) { // see if the existing property needs to be updated var prop = track.CustomPropertiesObj.FirstOrDefault(p => p.Name == property.Name); if (!string.Equals(prop.Value, property.Value)) { property.Value = prop.Value; updatesToProcess = true; } } else { // delete the property originalTrack.CustomPropertiesObj.Remove(property); updatesToProcess = true; } } } if (track.CustomPropertiesObj != null) { // add any new properties if (originalTrack.CustomProperties == null) { foreach (var property in track.CustomPropertiesObj) { originalTrack.CustomPropertiesObj.Add(property); updatesToProcess = true; } } else { foreach (var property in track.CustomPropertiesObj.Where(property => !originalTrack.CustomPropertiesObj.Contains(property))) { originalTrack.CustomPropertiesObj.Add(property); updatesToProcess = true; } } } if (updatesToProcess) { originalTrack.LastUpdatedByDate = DateTime.Now; originalTrack.LastUpdatedByUserId = UserInfo.UserID; TrackDataAccess.UpdateItem(originalTrack); } var savedTrack = TrackDataAccess.GetItem(track.TrackId, track.CodeCampId); var response = new ServiceResponse <TrackInfo> { Content = savedTrack }; return(Request.CreateResponse(HttpStatusCode.OK, response.ObjectToJson())); } catch (Exception ex) { Exceptions.LogException(ex); return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ERROR_MESSAGE)); } }
private async Task TryFillFromMoeAtHome(TrackInfo track, TrackMediaMetadata meta) { try { var uri = await _moeAtHome.GetLyrics(track.Title, track.Artist); if (uri != null) meta.Lyrics = await _lyricsCache.Download(track.Title, track.Artist, uri); } catch { } }
public static void ImportPlaylistToLibrary(string path, PrimarySource source, DatabaseImportManager importer) { try { Log.InformationFormat("Importing playlist {0} to library", path); SafeUri uri = new SafeUri(path); PlaylistParser parser = new PlaylistParser(); string relative_dir = System.IO.Path.GetDirectoryName(uri.LocalPath); if (relative_dir[relative_dir.Length - 1] != System.IO.Path.DirectorySeparatorChar) { relative_dir = relative_dir + System.IO.Path.DirectorySeparatorChar; } parser.BaseUri = new Uri(relative_dir); if (parser.Parse(uri)) { List <string> uris = new List <string> (); foreach (Dictionary <string, object> element in parser.Elements) { Uri elt = (Uri)element["uri"]; if (elt.IsFile) { uris.Add(elt.LocalPath); } else { Log.InformationFormat("Ignoring invalid playlist element: {0}", elt.OriginalString); } } if (source == null) { if (uris.Count > 0) { // Get the media attribute of the 1st Uri in Playlist // and then determine whether the playlist belongs to Video or Music SafeUri uri1 = new SafeUri(uris[0]); var track = new TrackInfo(); StreamTagger.TrackInfoMerge(track, uri1); if (track.HasAttribute(TrackMediaAttributes.VideoStream)) { source = ServiceManager.SourceManager.VideoLibrary; } else { source = ServiceManager.SourceManager.MusicLibrary; } } } // Give source a fallback value - MusicLibrary when it's null if (source == null) { source = ServiceManager.SourceManager.MusicLibrary; } // Only import an non-empty playlist if (uris.Count > 0) { ImportPlaylistWorker worker = new ImportPlaylistWorker( parser.Title, uris.ToArray(), source, importer); worker.Import(); } } } catch (Exception e) { Hyena.Log.Exception(e); } }
public void Open(TrackInfo track) { OpenPlay(track, false); }
protected abstract void RenderTrackInfo(Cairo.Context cr, TrackInfo track, bool renderTrack, bool renderArtistAlbum);
public void OpenPlay(TrackInfo track) { OpenPlay(track, true); }
public virtual bool GetTrackPath(TrackInfo track, out string path) { path = null; return(false); }
// For use by RadioTrackInfo // TODO remove this method once RadioTrackInfo playlist downloading/parsing logic moved here? internal void StartSynthesizeContacting(TrackInfo track) { //OnStateChanged (PlayerState.Contacting); RaiseEvent(new PlayerEventStateChangeArgs(CurrentState, PlayerState.Contacting)); synthesized_contacting_track = track; }
public WikipediaSongQuery(TrackInfo track) { this.track = track; }
public bool IsPlaying(TrackInfo track) { return(IsPlaying() && track != null && track.TrackEqual(CurrentTrack)); }