Exemple #1
0
 static public List<UVoicePart> Load(string file, UProject project)
 {
     List<UVoicePart> resultParts = new List<UVoicePart>();
     MidiFile midi = new MidiFile(file);
     for (int i = 0; i < midi.Tracks; i++)
     {
         Dictionary<int, UVoicePart> parts = new Dictionary<int, UVoicePart>();
         foreach (var e in midi.Events.GetTrackEvents(i))
             if (e is NoteOnEvent)
             {
                 var _e = e as NoteOnEvent;
                 if (!parts.ContainsKey(_e.Channel)) parts.Add(_e.Channel, new UVoicePart());
                 var note = project.CreateNote(
                     _e.NoteNumber,
                     (int)_e.AbsoluteTime * project.Resolution / midi.DeltaTicksPerQuarterNote,
                     _e.NoteLength * project.Resolution / midi.DeltaTicksPerQuarterNote);
                 parts[e.Channel].Notes.Add(note);
             }
         foreach (var pair in parts)
         {
             pair.Value.DurTick = pair.Value.GetMinDurTick(project);
             resultParts.Add(pair.Value);
         }
     }
     return resultParts;
 }
Exemple #2
0
        static public void Load(string[] files)
        {
            bool ustTracks = true;
            foreach (string file in files)
            {
                if (OpenUtau.Core.Formats.Formats.DetectProjectFormat(file) != Core.Formats.ProjectFormats.Ust) { ustTracks = false; break; }
            }

            if (!ustTracks)
            {
                DocManager.Inst.ExecuteCmd(new UserMessageNotification("Multiple files must be all Ust files"));
                return;
            }

            List<UProject> projects = new List<UProject>();
            foreach (string file in files)
            {
                projects.Add(Load(file));
            }

            double bpm = projects.First().BPM;
            UProject project = new UProject() { BPM = bpm, Name = "Merged Project", Saved = false };
            foreach (UProject p in projects)
            {
                var _track = p.Tracks[0];
                var _part = p.Parts[0];
                _track.TrackNo = project.Tracks.Count;
                _part.TrackNo = _track.TrackNo;
                project.Tracks.Add(_track);
                project.Parts.Add(_part);
            }

            if (project != null) DocManager.Inst.ExecuteCmd(new LoadProjectNotification(project));
        }
 private ISampleProvider BuildWavePartAudio(UWavePart part, UProject project)
 {
     AudioFileReader stream;
     try { stream = new AudioFileReader(part.FilePath); }
     catch { return null; }
     return new WaveToSampleProvider(stream);
 }
 public RemoveTrackCommand(UProject project, UTrack track)
 {
     this.project = project;
     this.track = track;
     foreach (var part in project.Parts)
         if (part.TrackNo == track.TrackNo)
             removedParts.Add(part);
 }
 public MovePartCommand(UProject project, UPart part, int newPos, int newTrackNo)
 {
     this.project = project;
     this.part = part;
     this.newPos = newPos;
     this.newTrackNo = newTrackNo;
     this.oldPos = part.PosTick;
     this.oldTrackNo = part.TrackNo;
 }
 public void ResamplePart(UVoicePart part, UProject project, IResamplerDriver engine, Action<SequencingSampleProvider> resampleDoneCallback)
 {
     this.resampleDoneCallback = resampleDoneCallback;
     BackgroundWorker worker = new BackgroundWorker();
     worker.WorkerReportsProgress = true;
     worker.DoWork += worker_DoWork;
     worker.RunWorkerCompleted += worker_RunWorkerCompleted;
     worker.ProgressChanged += worker_ProgressChanged;
     worker.RunWorkerAsync(new Tuple<UVoicePart, UProject, IResamplerDriver>(part, project, engine));
 }
Exemple #7
0
        public override int GetMinDurTick(UProject project)
        {
            int durTick = 0;

            foreach (UNote note in Notes)
            {
                durTick = Math.Max(durTick, note.PosTick + note.DurTick);
            }
            return(durTick);
        }
 public void Play(UProject project)
 {
     if (pendingParts > 0) return;
     else if (outDevice != null)
     {
         if (outDevice.PlaybackState == PlaybackState.Playing) return;
         else if (outDevice.PlaybackState == PlaybackState.Paused) { outDevice.Play(); return; }
         else outDevice.Dispose();
     }
     BuildAudio(project);
 }
        private void BuildVoicePartDone(SequencingSampleProvider source, UPart part, UProject project)
        {
            lock (lockObject)
            {
                trackSources[part.TrackNo].AddSource(
                    source,
                    TimeSpan.FromMilliseconds(project.TickToMillisecond(part.PosTick)));
                pendingParts--;
            }

            if (pendingParts == 0) StartPlayback();
        }
        private List<RenderItem> RenderAsync(UVoicePart part, UProject project, IResamplerDriver engine, BackgroundWorker worker)
        {
            List<RenderItem> renderItems = new List<RenderItem>();
            System.Diagnostics.Stopwatch watch = new Stopwatch();
            watch.Start();
            System.Diagnostics.Debug.WriteLine("Resampling start");
            lock (part)
            {
                string cacheDir = PathManager.Inst.GetCachePath(project.FilePath);
                string[] cacheFiles = Directory.EnumerateFiles(cacheDir).ToArray();
                int count = 0, i = 0;
                foreach (UNote note in part.Notes) foreach (UPhoneme phoneme in note.Phonemes) count++;

                foreach (UNote note in part.Notes)
                {
                    foreach (UPhoneme phoneme in note.Phonemes)
                    {
                        RenderItem item = BuildRenderItem(phoneme, part, project);
                        var sound = RenderCache.Inst.Get(item.HashParameters());

                        if (sound == null)
                        {
                            string cachefile = Path.Combine(cacheDir, string.Format("{0:x}.wav", item.HashParameters()));
                            if (!cacheFiles.Contains(cachefile))
                            {
                                System.Diagnostics.Debug.WriteLine("Sound {0:x} resampling {1}", item.HashParameters(), item.GetResamplerExeArgs());
                                DriverModels.EngineInput engineArgs = DriverModels.CreateInputModel(item, 0);
                                System.IO.Stream output = engine.DoResampler(engineArgs);
                                sound = new CachedSound(output);
                            }
                            else
                            {
                                System.Diagnostics.Debug.WriteLine("Sound {0:x} found on disk {1}", item.HashParameters(), item.GetResamplerExeArgs());
                                sound = new CachedSound(cachefile);
                            }
                            RenderCache.Inst.Put(item.HashParameters(), sound, engine.GetInfo().ToString());
                        }
                        else System.Diagnostics.Debug.WriteLine("Sound {0} found in cache {1}", item.HashParameters(), item.GetResamplerExeArgs());

                        item.Sound = sound;
                        renderItems.Add(item);
                        worker.ReportProgress(100 * ++i / count, string.Format("Resampling \"{0}\" {1}/{2}", phoneme.Phoneme, i, count));
                    }
                }
            }
            watch.Stop();
            System.Diagnostics.Debug.WriteLine("Resampling end");
            System.Diagnostics.Debug.WriteLine("Total cache size {0:n0} bytes", RenderCache.Inst.TotalMemSize);
            System.Diagnostics.Debug.WriteLine("Total time {0} ms", watch.Elapsed.TotalMilliseconds);
            return renderItems;
        }
Exemple #11
0
 public void ExecuteCmd(UCommand cmd, bool quiet = false)
 {
     if (cmd is UNotification)
     {
         if (cmd is SaveProjectNotification)
         {
             var _cmd = cmd as SaveProjectNotification;
             if (undoQueue.Count > 0) savedPoint = undoQueue.Last();
             if (_cmd.Path == "") OpenUtau.Core.Formats.USTx.Save(Project.FilePath, Project);
             else OpenUtau.Core.Formats.USTx.Save(_cmd.Path, Project);
         }
         else if (cmd is LoadProjectNotification)
         {
             undoQueue.Clear();
             redoQueue.Clear();
             undoGroup = null;
             savedPoint = null;
             this._project = ((LoadProjectNotification)cmd).project;
             this.playPosTick = 0;
         }
         else if (cmd is SetPlayPosTickNotification)
         {
             var _cmd = cmd as SetPlayPosTickNotification;
             this.playPosTick = _cmd.playPosTick;
         }
         Publish(cmd);
         if (!quiet) System.Diagnostics.Debug.WriteLine("Publish notification " + cmd.ToString());
         return;
     }
     else if (undoGroup == null) { System.Diagnostics.Debug.WriteLine("Null undoGroup"); return; }
     else
     {
         undoGroup.Commands.Add(cmd);
         cmd.Execute();
         Publish(cmd);
     }
     if (!quiet) System.Diagnostics.Debug.WriteLine("ExecuteCmd " + cmd.ToString());
 }
Exemple #12
0
 public override int GetMinDurTick(UProject project) { return 60; }
Exemple #13
0
 public abstract int GetMinDurTick(UProject project);
Exemple #14
0
 public override int GetMinDurTick(UProject project)
 {
     int durTick = 0;
     foreach (UNote note in Notes) durTick = Math.Max(durTick, note.PosTick + note.DurTick);
     return durTick;
 }
Exemple #15
0
 public void OnNext(UCommand cmd, bool isUndo)
 {
     if (cmd is PartCommand)
     {
         var _cmd = cmd as PartCommand;
         if (_cmd.part != _partContainer.Part) return;
         else if (_cmd is RemovePartCommand) _partContainer.Part = null;
     }
     else if (cmd is UNotification)
     {
         var _cmd = cmd as UNotification;
         if (_cmd is LoadPartNotification) { if (!(_cmd.part is UVoicePart)) return; _partContainer.Part = (UVoicePart)_cmd.part; _project = _cmd.project; }
         else if (_cmd is LoadProjectNotification) OnProjectLoad(_cmd);
     }
 }
Exemple #16
0
        static public UProject Load(string file, Encoding encoding = null)
        {
            int currentNoteIndex = 0;
            UstVersion version = UstVersion.Early;
            UstBlock currentBlock = UstBlock.None;
            string[] lines;

            try
            {
                if (encoding == null) lines = File.ReadAllLines(file, EncodingUtil.DetectFileEncoding(file));
                else lines = File.ReadAllLines(file, encoding);
            }
            catch (Exception e)
            {
                DocManager.Inst.ExecuteCmd(new UserMessageNotification(e.GetType().ToString() + "\n" + e.Message));
                return null;
            }

            UProject project = new UProject() { Resolution = 480, FilePath = file, Saved = false };
            project.RegisterExpression(new IntExpression(null, "velocity","VEL") { Data = 100, Min = 0, Max = 200});
            project.RegisterExpression(new IntExpression(null, "volume","VOL") { Data = 100, Min = 0, Max = 200});
            project.RegisterExpression(new IntExpression(null, "gender","GEN") { Data = 0, Min = -100, Max = 100});
            project.RegisterExpression(new IntExpression(null, "lowpass","LPF") { Data = 0, Min = 0, Max = 100});
            project.RegisterExpression(new IntExpression(null, "highpass", "HPF") { Data = 0, Min = 0, Max = 100 });
            project.RegisterExpression(new IntExpression(null, "accent", "ACC") { Data = 100, Min = 0, Max = 200 });
            project.RegisterExpression(new IntExpression(null, "decay", "DEC") { Data = 0, Min = 0, Max = 100 });

            var _track = new UTrack();
            project.Tracks.Add(_track);
            _track.TrackNo = 0;
            UVoicePart part = new UVoicePart() { TrackNo = 0, PosTick = 0 };
            project.Parts.Add(part);

            List<string> currentLines = new List<string>();
            int currentTick = 0;
            UNote currentNote = null;

            foreach (string line in lines)
            {
                if (line.Trim().StartsWith(@"[#") && line.Trim().EndsWith(@"]"))
                {
                    if (line.Equals(versionTag)) currentBlock = UstBlock.Version;
                    else if (line.Equals(settingTag)) currentBlock = UstBlock.Setting;
                    else
                    {
                        if (line.Equals(endTag)) currentBlock = UstBlock.Trackend;
                        else
                        {
                            try { currentNoteIndex = int.Parse(line.Replace("[#", "").Replace("]", "")); }
                            catch { DocManager.Inst.ExecuteCmd(new UserMessageNotification("Unknown ust format")); return null; }
                            currentBlock = UstBlock.Note;
                        }

                        if (currentLines.Count != 0)
                        {
                            currentNote = NoteFromUst(project.CreateNote(), currentLines, version);
                            currentNote.PosTick = currentTick;
                            if (!currentNote.Lyric.Replace("R", "").Replace("r", "").Equals("")) part.Notes.Add(currentNote);
                            currentTick += currentNote.DurTick;
                            currentLines.Clear();
                        }
                    }
                }
                else
                {
                    if (currentBlock == UstBlock.Version) {
                        if (line.StartsWith("UST Version"))
                        {
                            string v = line.Trim().Replace("UST Version", "");
                            if (v == "1.0") version = UstVersion.V1_0;
                            else if (v == "1.1") version = UstVersion.V1_1;
                            else if (v == "1.2") version = UstVersion.V1_2;
                            else version = UstVersion.Unknown;
                        }
                    }
                    if (currentBlock == UstBlock.Setting)
                    {
                        if (line.StartsWith("Tempo="))
                        {
                            project.BPM = double.Parse(line.Trim().Replace("Tempo=", ""));
                            if (project.BPM == 0) project.BPM = 120;
                        }
                        if (line.StartsWith("ProjectName=")) project.Name = line.Trim().Replace("ProjectName=", "");
                        if (line.StartsWith("VoiceDir="))
                        {
                            string singerpath = line.Trim().Replace("VoiceDir=", "");
                            var singer = UtauSoundbank.GetSinger(singerpath, EncodingUtil.DetectFileEncoding(file), DocManager.Inst.Singers);
                            if (singer == null) singer = new USinger() { Name = "", Path = singerpath };
                            project.Singers.Add(singer);
                            project.Tracks[0].Singer = singer;
                        }
                    }
                    else if (currentBlock == UstBlock.Note)
                    {
                        currentLines.Add(line);
                    }
                    else if (currentBlock == UstBlock.Trackend)
                    {
                        break;
                    }
                }
            }

            if (currentBlock != UstBlock.Trackend)
                DocManager.Inst.ExecuteCmd(new UserMessageNotification("Unexpected ust file end"));
            part.DurTick = currentTick;
            return project;
        }
 public LoadPartNotification(UPart part, UProject project) { this.part = part; this.project = project; }
 public ResizePartCommand(UProject project, UPart part, int newDur) { this.project = project; this.part = part; this.newDur = newDur; this.oldDur = part.DurTick; }
        private void BuildAudio(UProject project)
        {
            trackSources = new List<TrackSampleProvider>();
            foreach (UTrack track in project.Tracks)
            {
                trackSources.Add(new TrackSampleProvider() { Volume = DecibelToVolume(track.Volume) });
            }
            pendingParts = project.Parts.Count;
            foreach (UPart part in project.Parts)
            {
                if (part is UWavePart)
                {
                    lock (lockObject)
                    {
                        trackSources[part.TrackNo].AddSource(
                            BuildWavePartAudio(part as UWavePart, project),
                            TimeSpan.FromMilliseconds(project.TickToMillisecond(part.PosTick)));
                        pendingParts--;
                    }
                }
                else
                {
                    var singer = project.Tracks[part.TrackNo].Singer;
                    if (singer != null && singer.Loaded)
                    {
                        System.IO.FileInfo ResamplerFile = new System.IO.FileInfo(PathManager.Inst.GetPreviewEnginePath());
                        IResamplerDriver engine = ResamplerDriver.ResamplerDriver.LoadEngine(ResamplerFile.FullName);
                        BuildVoicePartAudio(part as UVoicePart, project, engine);
                    }
                    else lock (lockObject) { pendingParts--; }
                }
            }

            if (pendingParts == 0) StartPlayback();
        }
 public RemovePartCommand(UProject project, UPart part) { this.project = project; this.part = part; }
        private RenderItem BuildRenderItem(UPhoneme phoneme, UVoicePart part, UProject project)
        {
            USinger singer = project.Tracks[part.TrackNo].Singer;
            string rawfile = Lib.EncodingUtil.ConvertEncoding(singer.FileEncoding, singer.PathEncoding, phoneme.Oto.File);
            rawfile = Path.Combine(singer.Path, rawfile);

            double strechRatio = Math.Pow(2, 1.0 - (double)(int)phoneme.Parent.Expressions["velocity"].Data / 100);
            double length = phoneme.Oto.Preutter * strechRatio + phoneme.Envelope.Points[4].X;
            double requiredLength = Math.Ceiling(length / 50 + 1) * 50;
            double lengthAdjustment = phoneme.TailIntrude == 0 ? phoneme.Preutter : phoneme.Preutter - phoneme.TailIntrude + phoneme.TailOverlap;

            RenderItem item = new RenderItem()
            {
                // For resampler
                RawFile = rawfile,
                NoteNum = phoneme.Parent.NoteNum,
                Velocity = (int)phoneme.Parent.Expressions["velocity"].Data,
                Volume = (int)phoneme.Parent.Expressions["volume"].Data,
                StrFlags = phoneme.Parent.GetResamplerFlags(),
                PitchData = BuildPitchData(phoneme, part, project),
                RequiredLength = (int)requiredLength,
                Oto = phoneme.Oto,
                Tempo = project.BPM,

                // For connector
                SkipOver = phoneme.Oto.Preutter * strechRatio - phoneme.Preutter,
                PosMs = project.TickToMillisecond(part.PosTick + phoneme.Parent.PosTick + phoneme.PosTick) - phoneme.Preutter,
                DurMs = project.TickToMillisecond(phoneme.DurTick) + lengthAdjustment,
                Envelope = phoneme.Envelope.Points
            };

            return item;
        }
Exemple #22
0
            public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
            {
                UProject result = new UProject();
                string ustxVersion = dictionary["ustxversion"] as string;
                USTx.Project = result;
                result.Name = dictionary["name"] as string;
                result.Comment = dictionary["comment"] as string;
                result.OutputDir = dictionary["output"] as string;
                result.CacheDir = dictionary["cache"] as string;
                result.BPM = Convert.ToDouble(dictionary["bpm"]);
                result.BeatPerBar = Convert.ToInt32(dictionary["bpbar"]);
                result.BeatUnit = Convert.ToInt32(dictionary["bunit"]);
                result.Resolution = Convert.ToInt32(dictionary["res"]);

                foreach (var pair in (Dictionary<string, object>)(dictionary["exptable"]))
                {
                    var exp = serializer.ConvertToType(pair.Value, typeof(IntExpression)) as IntExpression;
                    var _exp = new IntExpression(null, pair.Key, exp.Abbr)
                    {
                        Data = exp.Data,
                        Min = exp.Min,
                        Max = exp.Max,
                    };
                    result.ExpressionTable.Add(pair.Key, _exp);
                }

                var singers = dictionary["singers"] as ArrayList;
                foreach (var singer in singers)
                    result.Singers.Add(serializer.ConvertToType(singer, typeof(USinger)) as USinger);

                foreach (var track in dictionary["tracks"] as ArrayList)
                {
                    var _tarck = serializer.ConvertToType(track, typeof(UTrack)) as UTrack;
                    result.Tracks.Add(_tarck);
                }

                foreach (var part in dictionary["parts"] as ArrayList)
                    result.Parts.Add(serializer.ConvertToType(part, typeof(UPart)) as UPart);

                USTx.Project = null;
                return result;
            }
Exemple #23
0
 public static UProject Create()
 {
     UProject project = new UProject() { Saved = false };
     project.RegisterExpression(new IntExpression(null, "velocity", "VEL") { Data = 100, Min = 0, Max = 200 });
     project.RegisterExpression(new IntExpression(null, "volume", "VOL") { Data = 100, Min = 0, Max = 200 });
     project.RegisterExpression(new IntExpression(null, "gender", "GEN") { Data = 0, Min = -100, Max = 100 });
     project.RegisterExpression(new IntExpression(null, "lowpass", "LPF") { Data = 0, Min = 0, Max = 100 });
     project.RegisterExpression(new IntExpression(null, "highpass", "HPF") { Data = 0, Min = 0, Max = 100 });
     project.RegisterExpression(new IntExpression(null, "accent", "ACC") { Data = 100, Min = 0, Max = 200 });
     project.RegisterExpression(new IntExpression(null, "decay", "DEC") { Data = 0, Min = 0, Max = 100 });
     return project;
 }
 public TrackChangeSingerCommand(UProject project, UTrack track, USinger newSinger) { this.project = project; this.track = track; this.newSinger = newSinger; this.oldSinger = track.Singer; }
 public LoadProjectNotification(UProject project) { this.project = project; }
 public AddTrackCommand(UProject project, UTrack track) { this.project = project; this.track = track; }
        private List<int> BuildPitchData(UPhoneme phoneme, UVoicePart part, UProject project)
        {
            List<int> pitches = new List<int>();
            UNote lastNote = part.Notes.OrderByDescending(x => x).Where(x => x.CompareTo(phoneme.Parent) < 0).FirstOrDefault();
            UNote nextNote = part.Notes.Where(x => x.CompareTo(phoneme.Parent) > 0).FirstOrDefault();
            // Get relevant pitch points
            List<PitchPoint> pps = new List<PitchPoint>();

            bool lastNoteInvolved = lastNote != null && phoneme.Overlapped;
            bool nextNoteInvolved = nextNote != null && nextNote.Phonemes[0].Overlapped;

            double lastVibratoStartMs = 0;
            double lastVibratoEndMs = 0;
            double vibratoStartMs = 0;
            double vibratoEndMs = 0;

            if (lastNoteInvolved)
            {
                double offsetMs = DocManager.Inst.Project.TickToMillisecond(phoneme.Parent.PosTick - lastNote.PosTick);
                foreach (PitchPoint pp in lastNote.PitchBend.Points)
                {
                    var newpp = pp.Clone();
                    newpp.X -= offsetMs;
                    newpp.Y -= (phoneme.Parent.NoteNum - lastNote.NoteNum) * 10;
                    pps.Add(newpp);
                }
                if (lastNote.Vibrato.Depth != 0)
                {
                    lastVibratoStartMs = -DocManager.Inst.Project.TickToMillisecond(lastNote.DurTick) * lastNote.Vibrato.Length / 100;
                    lastVibratoEndMs = 0;
                }
            }

            foreach (PitchPoint pp in phoneme.Parent.PitchBend.Points) pps.Add(pp);
            if (phoneme.Parent.Vibrato.Depth != 0)
            {
                vibratoEndMs = DocManager.Inst.Project.TickToMillisecond(phoneme.Parent.DurTick);
                vibratoStartMs = vibratoEndMs * (1 - phoneme.Parent.Vibrato.Length / 100);
            }

            if (nextNoteInvolved)
            {
                double offsetMs = DocManager.Inst.Project.TickToMillisecond(phoneme.Parent.PosTick - nextNote.PosTick);
                foreach (PitchPoint pp in nextNote.PitchBend.Points)
                {
                    var newpp = pp.Clone();
                    newpp.X -= offsetMs;
                    newpp.Y -= (phoneme.Parent.NoteNum - nextNote.NoteNum) * 10;
                    pps.Add(newpp);
                }
            }

            double startMs = DocManager.Inst.Project.TickToMillisecond(phoneme.PosTick) - phoneme.Oto.Preutter;
            double endMs = DocManager.Inst.Project.TickToMillisecond(phoneme.DurTick) -
                (nextNote != null && nextNote.Phonemes[0].Overlapped ? nextNote.Phonemes[0].Preutter - nextNote.Phonemes[0].Overlap : 0);
            if (pps.Count > 0)
            {
                if (pps.First().X > startMs) pps.Insert(0, new PitchPoint(startMs, pps.First().Y));
                if (pps.Last().X < endMs) pps.Add(new PitchPoint(endMs, pps.Last().Y));
            }
            else
            {
                throw new Exception("Zero pitch points.");
            }

            // Interpolation
            const int intervalTick = 5;
            double intervalMs = DocManager.Inst.Project.TickToMillisecond(intervalTick);
            double currMs = startMs;
            int i = 0;

            while (currMs < endMs)
            {
                while (pps[i + 1].X < currMs) i++;
                double pit = MusicMath.InterpolateShape(pps[i].X, pps[i + 1].X, pps[i].Y, pps[i + 1].Y, currMs, pps[i].Shape);
                pit *= 10;

                // Apply vibratos
                if (currMs < lastVibratoEndMs && currMs >= lastVibratoStartMs)
                    pit += InterpolateVibrato(lastNote.Vibrato, currMs - lastVibratoStartMs);

                if (currMs < vibratoEndMs && currMs >= vibratoStartMs)
                    pit += InterpolateVibrato(phoneme.Parent.Vibrato, currMs - vibratoStartMs);

                pitches.Add((int)pit);
                currMs += intervalMs;
            }

            return pitches;
        }
Exemple #28
0
 DocManager() {
     _project = new UProject();
 }
Exemple #29
0
 public static void Save(string file, UProject project)
 {
     JavaScriptSerializer jss = new JavaScriptSerializer();
     jss.RegisterConverters(
         new List<JavaScriptConverter>()
             {
                 new UProjectConvertor(),
                 new MiscConvertor(),
                 new UPartConvertor(),
                 new UNoteConvertor(),
                 new UPhonemeConverter()
             });
     StringBuilder str = new StringBuilder();
     try
     {
         jss.Serialize(project, str);
         var f_out = new StreamWriter(file);
         f_out.Write(str.ToString());
         f_out.Close();
         project.Saved = true;
         project.FilePath = file;
     }
     catch (Exception e)
     {
         System.Diagnostics.Debug.WriteLine(e.ToString());
     }
 }
Exemple #30
0
 public abstract int GetMinDurTick(UProject project);
 private void BuildVoicePartAudio(UVoicePart part, UProject project,IResamplerDriver engine)
 {
     ResamplerInterface ri = new ResamplerInterface();
     ri.ResamplePart(part, project, engine, (o) => { this.BuildVoicePartDone(o, part, project); });
 }
Exemple #32
0
 public override int GetMinDurTick(UProject project)
 {
     return(60);
 }
Exemple #33
0
        static public UProject Load(string file)
        {
            XmlDocument vsqx = new XmlDocument();

            try
            {
                vsqx.Load(file);
            }
            catch (Exception e)
            {
                System.Windows.MessageBox.Show(e.GetType().ToString() + "\n" + e.Message);
                return null;
            }

            XmlNamespaceManager nsmanager = new XmlNamespaceManager(vsqx.NameTable);
            nsmanager.AddNamespace("v3", vsq3NameSpace);
            nsmanager.AddNamespace("v4", vsq4NameSpace);

            XmlNode root;
            string nsPrefix;

            // Detect vsqx version
            root = vsqx.SelectSingleNode("v3:vsq3", nsmanager);

            if (root != null) nsPrefix = "v3:";
            else
            {
                root = vsqx.SelectSingleNode("v4:vsq4", nsmanager);

                if (root != null) nsPrefix = "v4:";
                else
                {
                    System.Windows.MessageBox.Show("Unrecognizable VSQx file format.");
                    return null;
                }
            }

            UProject uproject = new UProject();
            uproject.RegisterExpression(new IntExpression(null, "velocity", "VEL") { Data = 64, Min = 0, Max = 127 });
            uproject.RegisterExpression(new IntExpression(null, "volume", "VOL") { Data = 100, Min = 0, Max = 200 });
            uproject.RegisterExpression(new IntExpression(null, "opening", "OPE") { Data = 127, Min = 0, Max = 127 });
            uproject.RegisterExpression(new IntExpression(null, "accent", "ACC") { Data = 50, Min = 0, Max = 100 });
            uproject.RegisterExpression(new IntExpression(null, "decay", "DEC") { Data = 50, Min = 0, Max = 100 });

            string bpmPath = string.Format("{0}masterTrack/{0}tempo/{0}{1}", nsPrefix, nsPrefix == "v3:" ? "bpm" : "v");
            string beatperbarPath = string.Format("{0}masterTrack/{0}timeSig/{0}{1}", nsPrefix, nsPrefix == "v3:" ? "nume" : "nu");
            string beatunitPath = string.Format("{0}masterTrack/{0}timeSig/{0}{1}", nsPrefix, nsPrefix == "v3:" ? "denomi" : "de");
            string premeasurePath = string.Format("{0}masterTrack/{0}preMeasure", nsPrefix);
            string resolutionPath = string.Format("{0}masterTrack/{0}resolution", nsPrefix);
            string projectnamePath = string.Format("{0}masterTrack/{0}seqName", nsPrefix);
            string projectcommentPath = string.Format("{0}masterTrack/{0}comment", nsPrefix);
            string trackPath = string.Format("{0}vsTrack", nsPrefix);
            string tracknamePath = string.Format("{0}{1}", nsPrefix, nsPrefix == "v3:" ? "trackName" : "name");
            string trackcommentPath = string.Format("{0}comment", nsPrefix);
            string tracknoPath = string.Format("{0}{1}", nsPrefix, nsPrefix == "v3:" ? "vsTrackNo" : "tNo");
            string partPath = string.Format("{0}{1}", nsPrefix, nsPrefix == "v3:" ? "musicalPart" : "vsPart");
            string partnamePath = string.Format("{0}{1}", nsPrefix, nsPrefix == "v3:" ? "partName" : "name");
            string partcommentPath = string.Format("{0}comment", nsPrefix);
            string notePath = string.Format("{0}note", nsPrefix);
            string postickPath = string.Format("{0}{1}", nsPrefix, nsPrefix == "v3:" ? "posTick" : "t");
            string durtickPath = string.Format("{0}{1}", nsPrefix, nsPrefix == "v3:" ? "durTick" : "dur");
            string notenumPath = string.Format("{0}{1}", nsPrefix, nsPrefix == "v3:" ? "noteNum" : "n");
            string velocityPath = string.Format("{0}{1}", nsPrefix, nsPrefix == "v3:" ? "velocity" : "v");
            string lyricPath = string.Format("{0}{1}", nsPrefix, nsPrefix == "v3:" ? "lyric" : "y");
            string phonemePath = string.Format("{0}{1}", nsPrefix, nsPrefix == "v3:" ? "phnms" : "p");
            string playtimePath = string.Format("{0}playTime", nsPrefix);
            string partstyleattrPath = string.Format("{0}{1}/{0}{2}", nsPrefix, nsPrefix == "v3:" ? "partStyle" : "pStyle", nsPrefix == "v3:" ? "attr" : "v");
            string notestyleattrPath = string.Format("{0}{1}/{0}{2}", nsPrefix, nsPrefix == "v3:" ? "noteStyle" : "nStyle", nsPrefix == "v3:" ? "attr" : "v");

            uproject.BPM = Convert.ToDouble(root.SelectSingleNode(bpmPath, nsmanager).InnerText) / 100;
            uproject.BeatPerBar = int.Parse(root.SelectSingleNode(beatperbarPath, nsmanager).InnerText);
            uproject.BeatUnit = int.Parse(root.SelectSingleNode(beatunitPath, nsmanager).InnerText);
            uproject.Resolution = int.Parse(root.SelectSingleNode(resolutionPath, nsmanager).InnerText);
            uproject.FilePath = file;
            uproject.Name = root.SelectSingleNode(projectnamePath, nsmanager).InnerText;
            uproject.Comment = root.SelectSingleNode(projectcommentPath, nsmanager).InnerText;

            int preMeasure = int.Parse(root.SelectSingleNode(premeasurePath, nsmanager).InnerText);
            int partPosTickShift = -preMeasure * uproject.Resolution * uproject.BeatPerBar * 4 / uproject.BeatUnit;

            USinger usinger = new USinger();
            uproject.Singers.Add(usinger);

            foreach (XmlNode track in root.SelectNodes(trackPath, nsmanager)) // track
            {
                UTrack utrack = new UTrack() { Singer = usinger, TrackNo = uproject.Tracks.Count };
                uproject.Tracks.Add(utrack);

                utrack.Name = track.SelectSingleNode(tracknamePath, nsmanager).InnerText;
                utrack.Comment = track.SelectSingleNode(trackcommentPath, nsmanager).InnerText;
                utrack.TrackNo = int.Parse(track.SelectSingleNode(tracknoPath, nsmanager).InnerText);

                foreach (XmlNode part in track.SelectNodes(partPath, nsmanager)) // musical part
                {
                    UVoicePart upart = new UVoicePart();
                    uproject.Parts.Add(upart);

                    upart.Name = part.SelectSingleNode(partnamePath, nsmanager).InnerText;
                    upart.Comment = part.SelectSingleNode(partcommentPath, nsmanager).InnerText;
                    upart.PosTick = int.Parse(part.SelectSingleNode(postickPath, nsmanager).InnerText) + partPosTickShift;
                    upart.DurTick = int.Parse(part.SelectSingleNode(playtimePath, nsmanager).InnerText);
                    upart.TrackNo = utrack.TrackNo;

                    foreach (XmlNode note in part.SelectNodes(notePath, nsmanager))
                    {
                        UNote unote = uproject.CreateNote();

                        unote.PosTick = int.Parse(note.SelectSingleNode(postickPath, nsmanager).InnerText);
                        unote.DurTick = int.Parse(note.SelectSingleNode(durtickPath, nsmanager).InnerText);
                        unote.NoteNum = int.Parse(note.SelectSingleNode(notenumPath, nsmanager).InnerText);
                        unote.Lyric = note.SelectSingleNode(lyricPath, nsmanager).InnerText;
                        unote.Phonemes[0].Phoneme = note.SelectSingleNode(phonemePath, nsmanager).InnerText;

                        unote.Expressions["velocity"].Data = int.Parse(note.SelectSingleNode(velocityPath, nsmanager).InnerText);

                        foreach (XmlNode notestyle in note.SelectNodes(notestyleattrPath, nsmanager))
                        {
                            if (notestyle.Attributes["id"].Value == "opening")
                                unote.Expressions["opening"].Data = int.Parse(notestyle.InnerText);
                            else if (notestyle.Attributes["id"].Value == "accent")
                                unote.Expressions["accent"].Data = int.Parse(notestyle.InnerText);
                            else if (notestyle.Attributes["id"].Value == "decay")
                                unote.Expressions["decay"].Data = int.Parse(notestyle.InnerText);
                        }
                        unote.PitchBend.Points[0].X = -uproject.TickToMillisecond(Math.Min(15, unote.DurTick / 3));
                        unote.PitchBend.Points[1].X = -unote.PitchBend.Points[0].X;
                        upart.Notes.Add(unote);
                    }
                }
            }

            return uproject;
        }