Turn audio into a shareable video. forked from nypublicradio/audiogram

index.js 8.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. var d3 = require("d3"),
  2. $ = require("jquery"),
  3. preview = require("./preview.js"),
  4. video = require("./video.js"),
  5. audio = require("./audio.js");
  6. d3.json("/settings/labels.json", function(err, labels){
  7. // Populate labels menu
  8. d3.select("#input-label")
  9. .on("change", updateLabel)
  10. .selectAll("option")
  11. .data(labels.podcasts)
  12. .enter()
  13. .append("option")
  14. .text(function(l){
  15. return l;
  16. });
  17. d3.select("#input-label").each(updateLabel);
  18. }); // end label ingestion
  19. d3.json("/settings/themes.json", function(err, themes){
  20. var errorMessage;
  21. // Themes are missing or invalid
  22. if (err || !d3.keys(themes).filter(function(d){ return d !== "default"; }).length) {
  23. if (err instanceof SyntaxError) {
  24. errorMessage = "Error in settings/themes.json:<br/><code>" + err.toString() + "</code>";
  25. } else if (err instanceof ProgressEvent) {
  26. errorMessage = "Error: no settings/themes.json.";
  27. } else if (err) {
  28. errorMessage = "Error: couldn't load settings/themes.json.";
  29. } else {
  30. errorMessage = "No themes found in settings/themes.json.";
  31. }
  32. d3.select("#loading-bars").remove();
  33. d3.select("#loading-message").html(errorMessage);
  34. if (err) {
  35. throw err;
  36. }
  37. return;
  38. }
  39. for (var key in themes) {
  40. themes[key] = $.extend({}, themes.default, themes[key]);
  41. }
  42. preloadImages(themes);
  43. });
  44. function submitted() {
  45. d3.event.preventDefault();
  46. var theme = preview.theme(),
  47. caption = preview.caption(),
  48. citation = preview.citation(),
  49. label = preview.label(),
  50. selection = preview.selection(),
  51. file = preview.file(),
  52. identifier;
  53. // for easy-to-scan filenames
  54. identifier = caption.replace(/\s+/g, '_').replace(/\'|\"|\.|\?|\!/g, '').toLowerCase().slice(0, 20);
  55. if (!file) {
  56. d3.select("#row-audio").classed("error", true);
  57. return setClass("error", "No audio file selected.");
  58. }
  59. if (theme.maxDuration && selection.duration > theme.maxDuration) {
  60. return setClass("error", "Your Audiogram must be under " + theme.maxDuration + " seconds.");
  61. }
  62. if (!theme || !theme.width || !theme.height) {
  63. return setClass("error", "No valid theme detected.");
  64. }
  65. if (theme.labelText) {
  66. label = theme.labelText;
  67. }
  68. video.kill();
  69. audio.pause();
  70. var formData = new FormData();
  71. formData.append("audio", file);
  72. if (selection.start || selection.end) {
  73. formData.append("start", selection.start);
  74. formData.append("end", selection.end);
  75. }
  76. formData.append("theme", JSON.stringify($.extend({}, theme, { backgroundImageFile: null })));
  77. formData.append("caption", caption);
  78. formData.append("citation", citation);
  79. formData.append("label", label);
  80. formData.append("identifier", identifier);
  81. setClass("loading");
  82. d3.select("#loading-message").text("Uploading audio...");
  83. $.ajax({
  84. url: "/submit/",
  85. type: "POST",
  86. data: formData,
  87. contentType: false,
  88. dataType: "json",
  89. cache: false,
  90. processData: false,
  91. success: function(data){
  92. poll(data.id, 0);
  93. },
  94. error: error
  95. });
  96. }
  97. function poll(id) {
  98. var identifier = preview.caption().replace(/\s+/g, '_').replace(/\'|\"|\.|\?|\!/g, '').toLowerCase().slice(0, 20);
  99. setTimeout(function(){
  100. $.ajax({
  101. url: "/status/" + id + "/",
  102. error: error,
  103. dataType: "json",
  104. success: function(result){
  105. if (result && result.status && result.status === "ready" && result.url) {
  106. video.update(result.url, identifier);
  107. setClass("rendered");
  108. } else if (result.status === "error") {
  109. error(result.error);
  110. } else {
  111. d3.select("#loading-message").text(statusMessage(result));
  112. poll(id);
  113. }
  114. }
  115. });
  116. }, 2500);
  117. }
  118. function error(msg) {
  119. if (msg.responseText) {
  120. msg = msg.responseText;
  121. }
  122. if (typeof msg !== "string") {
  123. msg = JSON.stringify(msg);
  124. }
  125. if (!msg) {
  126. msg = "Unknown error";
  127. }
  128. d3.select("#loading-message").text("Loading...");
  129. setClass("error", msg);
  130. }
  131. // Once images are downloaded, set up listeners
  132. function initialize(err, themesWithImages) {
  133. // Populate themes menu
  134. d3.select("#input-theme")
  135. .on("change", updateTheme)
  136. .selectAll("option")
  137. .data(themesWithImages)
  138. .enter()
  139. .append("option")
  140. .text(function(d){
  141. return d.name;
  142. });
  143. // Get initial theme
  144. d3.select("#input-theme").each(updateTheme);
  145. // Get initial caption (e.g. back button)
  146. d3.select("#input-caption").on("change keyup", updateCaption).each(updateCaption);
  147. // Get initial citation (e.g. back button)
  148. d3.select("#input-citation").on("change keyup", updateCitation).each(updateCitation);
  149. // Space bar listener for audio play/pause
  150. d3.select(document).on("keypress", function(){
  151. if (!d3.select("body").classed("rendered") && d3.event.key === " " && !d3.matcher("input, textarea, button, select").call(d3.event.target)) {
  152. audio.toggle();
  153. }
  154. });
  155. // Button listeners
  156. d3.selectAll("#play, #pause").on("click", function(){
  157. d3.event.preventDefault();
  158. audio.toggle();
  159. });
  160. d3.select("#restart").on("click", function(){
  161. d3.event.preventDefault();
  162. audio.restart();
  163. });
  164. // If there's an initial piece of audio (e.g. back button) load it
  165. d3.select("#input-audio").on("change", updateAudioFile).each(updateAudioFile);
  166. d3.select("#return").on("click", function(){
  167. d3.event.preventDefault();
  168. video.kill();
  169. setClass(null);
  170. });
  171. d3.select("#submit").on("click", submitted);
  172. }
  173. function updateAudioFile() {
  174. d3.select("#row-audio").classed("error", false);
  175. audio.pause();
  176. video.kill();
  177. // Skip if empty
  178. if (!this.files || !this.files[0]) {
  179. d3.select("#minimap").classed("hidden", true);
  180. preview.file(null);
  181. setClass(null);
  182. return true;
  183. }
  184. d3.select("#loading-message").text("Analyzing...");
  185. setClass("loading");
  186. preview.loadAudio(this.files[0], function(err){
  187. if (err) {
  188. d3.select("#row-audio").classed("error", true);
  189. setClass("error", "Error decoding audio file");
  190. } else {
  191. setClass(null);
  192. }
  193. d3.selectAll("#minimap, #submit").classed("hidden", !!err);
  194. });
  195. }
  196. function updateCaption() {
  197. preview.caption(this.value);
  198. }
  199. function updateCitation() {
  200. preview.citation(this.value);
  201. }
  202. function updateLabel() {
  203. preview.label(this.value);
  204. }
  205. function updateTheme() {
  206. var theme_obj = d3.select(this.options[this.selectedIndex]).datum(),
  207. that = this;
  208. // Automatically set the label for themes that have them
  209. preview.theme(theme_obj);
  210. if (theme_obj.labelText) {
  211. preview.label(theme_obj.labelText);
  212. $('#input-label').children().each(function (i, c) {
  213. if (c.value === that.options[that.selectedIndex].value) {
  214. $(c).prop('selected', true);
  215. return false;
  216. }
  217. });
  218. $('#input-label').prop('disabled', true);
  219. }
  220. else {
  221. $('#input-label').prop('disabled', false);
  222. }
  223. }
  224. function preloadImages(themes) {
  225. // preload images
  226. var imageQueue = d3.queue();
  227. d3.entries(themes).forEach(function(theme){
  228. if (!theme.value.name) {
  229. theme.value.name = theme.key;
  230. }
  231. if (theme.key !== "default") {
  232. imageQueue.defer(getImage, theme.value);
  233. }
  234. });
  235. imageQueue.awaitAll(initialize);
  236. function getImage(theme, cb) {
  237. if (!theme.backgroundImage) {
  238. return cb(null, theme);
  239. }
  240. theme.backgroundImageFile = new Image();
  241. theme.backgroundImageFile.onload = function(){
  242. return cb(null, theme);
  243. };
  244. theme.backgroundImageFile.onerror = function(e){
  245. console.warn(e);
  246. return cb(null, theme);
  247. };
  248. theme.backgroundImageFile.src = "/settings/backgrounds/" + theme.backgroundImage;
  249. }
  250. }
  251. function setClass(cl, msg) {
  252. d3.select("body").attr("class", cl || null);
  253. d3.select("#error").text(msg || "");
  254. }
  255. function statusMessage(result) {
  256. switch (result.status) {
  257. case "queued":
  258. return "Waiting for other jobs to finish, #" + (result.position + 1) + " in queue";
  259. case "audio-download":
  260. return "Downloading audio for processing";
  261. case "trim":
  262. return "Trimming audio";
  263. case "probing":
  264. return "Probing audio file";
  265. case "waveform":
  266. return "Analyzing waveform";
  267. case "renderer":
  268. return "Initializing renderer";
  269. case "frames":
  270. var msg = "Generating frames";
  271. if (result.numFrames) {
  272. msg += ", " + Math.round(100 * (result.framesComplete || 0) / result.numFrames) + "% complete";
  273. }
  274. return msg;
  275. case "combine":
  276. return "Combining frames with audio";
  277. case "ready":
  278. return "Cleaning up";
  279. default:
  280. return JSON.stringify(result);
  281. }
  282. }