Wednesday, January 6, 2010

Code: Build an Adaptive Bitrate SMIL File Using XmlDocument

Code Snippet
  1. /// <summary>
  2. /// Builds a smil file based on .mp4 files found in a given directory
  3. /// Assumes files are named XXX_bitrate.mp4 (movie_300.mp4)
  4. /// </summary>
  5. public static XmlDocument BuildSmilFile(DirectoryInfo sourceDirectory)
  6. {
  7.     List<FileInfo> files = new List<FileInfo>();
  8.     files.AddRange(sourceDirectory.GetFiles("*.mp4"));
  9.  
  10.     //biggest file (highest bitrate) first.
  11.     files.Sort(delegate(FileInfo p1, FileInfo p2)
  12.     {
  13.         return p2.Length.CompareTo(p1.Length);
  14.     });
  15.  
  16.     XmlDocument result = new XmlDocument();
  17.  
  18.     //create element nodes
  19.     XmlNode smilNode = result.CreateElement("smil");
  20.     XmlNode headNode = result.CreateElement("head");
  21.     XmlNode bodyNode = result.CreateElement("body");
  22.     XmlNode switchNode = result.CreateElement("switch");
  23.  
  24.     //add video nodes for each file
  25.     foreach (FileInfo mp4File in files)
  26.     {
  27.         XmlNode videoNode = result.CreateElement("video");
  28.  
  29.         //Create and add attributes
  30.         XmlAttribute srcAttr = result.CreateAttribute("src");
  31.         srcAttr.Value = mp4File.Name;
  32.         XmlAttribute bitrateAttr = result.CreateAttribute("system-bitrate");
  33.         bitrateAttr.Value = Path.GetFileNameWithoutExtension(mp4File.Name).Substring(mp4File.Name.LastIndexOf("_") + 1) + "000";
  34.         videoNode.Attributes.Append(srcAttr);
  35.         videoNode.Attributes.Append(bitrateAttr);
  36.  
  37.         //add video node to switch
  38.         switchNode.AppendChild(videoNode);
  39.     }
  40.  
  41.     //append nodes to parent elements
  42.     bodyNode.AppendChild(switchNode);
  43.     smilNode.AppendChild(headNode);
  44.     smilNode.AppendChild(bodyNode);
  45.     result.AppendChild(smilNode);
  46.  
  47.     return result;
  48. }